可能重复:
Generating all permutations of a given string给定长度和字符集,如何得到所有可能的字符串组合
给定长度n=4,
和set of characters -> {'a', 'b'}
, 如何编写一些java代码来生成所有可能的字符串,其长度为n,包含集合中的字符?
对于上面的例子中,结果应该有2^4 = 16串,那就是:
aaaa
aaab
aabb
abbb
baaa
baab
babb
bbbb
bbaa
bbab
bbba
abaa
abab
abba
baba
aaba
这里是我的代码片段:
public void process(String result, String string)
{
if(string.length() == 0)
{
System.out.println(result);
}else{
for(int i = 0; i < string.length(); i++)
{
String newResult = new String(result+string.charAt(i));
String newString = new String(string.substring(0,i) + string.substring(i+1, string.length()));
process(newResult, newString);
}
}
}
这似乎只是在做置换,而不是我想要什么....... 预先感谢您:)
http:// stackoverflow。com/questions/4240080/generate-all-permutations-of-a-given-string –
@Matteo我试图从字符串排列中使用类似的代码,但是我没有得到正确的结果... –
转到理论第一:http://en.wikipedia.org/wiki/Permutations – davidmontoyago