在Java中优化字符串组合

时间:2014-10-23 19:42:18

标签: java

我需要从给定元素中获取长度为k的字符串的所有组合。例如,对于

char[] elements = {'a', 'b', 'c'}
k = 4

输出应该是:aaaa,aaab,...,cccc。现在我有以下代码,它们给出了正确的结果但是还不够快。我的代码可以改进什么?

public static ArrayList<String> printAllKLength(char[] elements, int nrElements, int patternLength) {
    ArrayList<String> patternVariations = new ArrayList<String>();
    patternVariations = printAllKLengthRec(elements, "", nrElements, patternLength, patternVariations);

    return patternVariations;
}

public static ArrayList<String> printAllKLengthRec(char[] elements, String prefix, int nrElements, int patternLength, ArrayList<String> patternVariations) {

    if (patternLength == 0) {
        patternVariations.add(prefix);
        //System.out.println(prefix);
        return patternVariations;
    }

    for (int i = 0; i < nrElements; ++i) {
        String newPrefix = prefix + elements[i]; 
        printAllKLengthRec(elements, newPrefix, nrElements, patternLength - 1, patternVariations); 
    }
    return patternVariations;
}

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用动态编程方法(记忆)。非常相似的东西:

http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/

答案 1 :(得分:0)

尝试不进行递归...请参阅此处的说明。

recursion versus iteration

我希望这有助于你