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

时间:2015-01-18 14:32:20

标签: java string performance algorithm design-patterns

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

例如,让我们考虑一个包含以下元素的数组:' 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;
        }
    }
}
}

1 个答案:

答案 0 :(得分:2)

结帐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);
                }
            }
        }
    }
相关问题