可能重复: Generating对一个给定的字符串所有排列
Possible Duplicate: Generating all permutations of a given string
由于长度 N = 4, 和字符集 - > {'A','B'} , 如何编写一些Java codeS产生所有可能的字符串包含在设定的字符长度为n?
Given a length n=4, and a set of characters -> {'a', 'b'}, how to write some java codes to produce all the possible string with that length n containing the characters in the set?
有关上面的例子中,结果应具有2 ^ 4 = 16字符串,它是:
For the example above, the result should have 2^4=16 strings, which is:
aaaa aaab aabb abbb baaa baab babb bbbb bbaa bbab bbba abaa abab abba baba aaba
这是我的code片断:
here is my code snippet:
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); } } }这似乎只是在做什么,而不是我想要的排列,....... 预先感谢您:)
That seems like only doing permutation, instead of what I want....... Thank you in advance :)
推荐答案把它以同样的方式将计数。你专门从AAAA计数到BBBB,像二进制。
Think of it in the same way you would counting. You're technically "counting" from aaaa to bbbb, like binary.
aaaa -> 0000 aaab -> 0001 aaba -> 0010 aabb -> 0011 ... bbbb -> 1111
没有看到你已经试过,我不能帮你不止于此,但本质上则需要通过它们计数列举你的最低的元素,你的最高元素之间的所有的数字。
Without seeing what you've tried, I can't help you more than that, but essentially you need to enumerate all the "numbers" between your "lowest" element and your "highest" element by counting up through them.
对于更高的元件数量,只是把你计算在基数较高计数。对于八素,集= {A,B,C,D,E,F,G,H},你会被计算在什么本质八:
For higher element counts, just treat your counting as counting in a higher base. For eight elements, Set = {a, b, c, d, e, f, g, h}, you would be counting up in what's essentially octal:
aaaa -> 0000 aaab -> 0001 ... aaah -> 0007 aaba -> 0010 ... hhhh -> 7777
这是你列举的0-9所有组合,带4的长度,从0000计数到9999相同的方式。
It's the same way you enumerate all the combinations of 0-9 with a length of 4, by counting from 0000 to 9999.
编辑:
感谢您发布您的code。你是正确的,你在做排列组合。更好的方法是使用多组合(组合在进排序组合组重复的元素)算法,像一个讨论的这里。
Thank you for posting your code. You're correct, you're doing permutations. A better way would be to use a multi-combination (combination with repeated elements in the ordererd combination set) algorithm like the one discussed here.