不建议提供完整的解决方案,但如果您想了解其背后的理论,则取决于您。
public void comb(String A[], String str, int pos, int length)
{
if (length == 0) {
System.out.println(str);
} else {
for (int i = pos; i < A.length; i++)
comb(A, str + A[i], i + 1, length - 1);
}
}
public static void main(String[] args) {
String myArray[] = {"c", "a", "t", "d","o","g"};
C c = new C();
for (int i = 0; i <= myArray.length; i++)
c.comb(myArray, "", 0, i);
}
在another answer 中,我简要解释了类似生成器的工作原理。
我还建议您了解Backtracking 和组合算法。
编辑:如果您想要将组合存储在数组中,我能想到的唯一方法是初始化有足够的空间来存储所有此类组合,例如:
private String[] combinations;
private int count;
public void comb(String A[], String str, int pos, int length)
{
if (length == 0) {
combinations[count] = str;
count++;
} else {
for (int i = pos; i < A.length; i++)
comb(A, str + A[i], i + 1, length - 1);
}
}
public void solve()
{
// 64 = C(6, 6) + C(6, 5) + C(6, 4) + C(6, 3) + C(6, 2) + C(6, 1) + C(6, 0)
// where C(n, k) = binomial coefficient function.
combinations = new String[64];
count = 0;
String myArray[] = {"c", "a", "t", "d","o","g"};
for (int i = 0; i <= myArray.length; i++)
comb(myArray, "", 0, i);
for (int i = 0; i < combinations.length; i++)
System.out.println(combinations[i]);
}
public static void main(String[] args) {
C c = new C();
c.solve();
}