我正在寻找一个数组中所有可能组合的列表。例如,考虑以下元素的数组:'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;
}
}
}
}
String
上使用+=
不是最好的选择,也许StringBuilder
会更好。 - StepTNT