//使用递归实现唯一组合
//我这里修改了使用前缀在递归中进行传递的思路,只需传递索引即可,因此可以将对象作为参数而不仅仅是字符串。
public static void main(String[] args) {
int k = 20;
Object[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Object[] chars = { 'a', 'b', 'c', 'd', 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
Object[] aux = new Object[k];
long start = System.currentTimeMillis();
combination(chars, 0, 0, k, aux);
System.out.println("Time: "+ (System.currentTimeMillis()-start));
}
public static void combination(Object[] s, int index, int next, int k,
Object[] aux) {
if (index == k) {
show(aux);
}else{
for (int i = next; i < s.length; i++) {
aux[index] = s[i];
combination(s, index + 1, i + 1, k, aux);
}
}
}
private static void show(Object[] x) {
for (int i = 0; i < x.length; i++)
System.out.print(x[i] + " ");
System.out.println();
}
}
AAB
和ABA
是相同的组合。我认为你的意思是排列(permutations),而不是组合(combinations)。 - David Hammen