我需要从给定元素中获取长度为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;
}
谢谢!
答案 0 :(得分:0)
您可以使用动态编程方法(记忆)。非常相似的东西:
答案 1 :(得分:0)