Java阵列随机字母组合(不是ArrayList)



嘿,我想创建一个程序,以字母(c,a,t,d,o,g)输出所有可能的字符串

喜欢

c
c,a
c,a,t
c,a,d
...
.....
......
etc

我想知道是否在不使用arraylist的情况下是否可以这样做?我浏览了其他问题,它们所拥有的只是ArrayList,而不仅仅是正常数组

我可以做类似的事情:

字符串myArray [] = {C,A,T,D,O,G}

然后从那里去?我不确定下一步该怎么做

谢谢

不建议提供完整的解决方案,但如果您想学习此理论背后的理论,则必须取决于您。

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);
}

在另一个答案中,我简要解释了类似发电机的工作方式。

我还建议您了解回溯和组合算法。

编辑:如果您想要的是将组合存储在数组中,我唯一能想到的就是用足够的空间初始化以存储所有此类组合,例如:

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();
}

最新更新