Java 搜索数组中所有可能的组合列表(算法)

Java Search all possible combo lists in the array (Algorithm)

我正在尝试查找数组中元素所有可能组合的列表。

例如,让我们考虑一个包含以下元素的数组:'A'、'B'、'C'、'D' .

如果我选择一个数字作为最大字符串长度,那么我想要获得最大长度的所有数组组合。例如:

5 = 最大数量;然后: A , AA, AAA, AAAA, AAAAA , AAAAB , AAAAC ...... DDDDD

我做了一个代码。它的速度还可以,直到最大数量为10。超过15,它开始很慢。

有人有更好的办法让它更快吗?

这是我的代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    HashSet<String> allResults = new HashSet<String>();
    // Create an alphabet to work with
    char[] alphabet = new char[] {'A','B','C','D'};
    // Find all possible combinations of this alphabet in the string size of 3
    StringExcersise.possibleStrings(15, alphabet,"", allResults);
    System.out.println(allResults.size());
}


    class StringExcersise {

public static void possibleStrings(int maxLength, char[] alphabet, String curr, HashSet<String> allResults) {
    // If the current string has reached it's maximum length
    if(curr.length() == maxLength) {
        allResults.add(curr);
        //System.out.println(curr);

    // Else add each letter from the alphabet to new strings and process these new strings again
    } else {
        for(int i = 0; i < alphabet.length; i++) {
            String oldCurr = curr;
            if(!allResults.contains(oldCurr))
                allResults.add(oldCurr);
            curr += alphabet[i];
            possibleStrings(maxLength,alphabet,curr,allResults);
            curr = oldCurr;
        }
    }
}
}

查看 Heap's Algorithm here

Java中的工作示例:

    private static void swap(int[] v, int i, int j) {
        int temp = v[i]; 
            v[i] = v[j];
            v[j] = temp;
    }

    public void permute(int[] v, int n) {
        if (n == 1) {
            System.out.println(Arrays.toString(v));
        } else {
            for (int i = 0; i < n; i++) {
                permute(v, n-1);
                if (n % 2 == 1) {
                    swap(v, 0, n-1);
                } else {
                    swap(v, i, n-1);
                }
            }
        }
    }