【发布时间】:2015-03-16 15:27:21
【问题描述】:
我正在尝试查找数组中所有可能的元素组合的列表。
例如,让我们考虑一个包含以下元素的数组:'A','B','C','D'。
如果我选择一个数字作为最大字符串长度,那么我希望数组的所有组合达到最大长度。例如:
5 = 最大数量;然后:A,AA,AAA,AAAA,AAAA,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;
}
}
}
}
【问题讨论】:
-
任何算法都会变慢,因为您的解决方案空间大约是 5 的幂 (n+1),对于 n=15,它超过一万亿次。
-
@Bohemian 哦,真的吗?那是巨大的..那么我可能需要考虑如何减少可能的组合.. :)
-
顺便说一句,如果您需要表演,在
String上使用+=可能不是最佳选择,也许StringBuilder可能是更好的选择。
标签: java string performance algorithm design-patterns