你需要更具体地了解你希望你的功能得到什么。 “组合”有许多不同的定义,您没有指定是否需要有序或无序组合。
在数学上,如果你有n个元素,并且想要一个k的LIST(按重复排序),那就给你了
n ^ k组合。 (原始示例中有6 ^ 4 = 1296种组合,这很多!)。但是,如果你有n个元素,并且想要一个k的MULTISET(重复无序),那就给你了
(n + k - 1)! / (k! * (n - 1)!)组合,是一个更难的枚举。
如果k很小,你可以用有限数量的for循环生成第一个,但随着k的增长,这变得非常麻烦。这强烈暗示需要RECURSIVE方法:
public static String[] getAllLists(String[] elements, int lengthOfList)
{
//initialize our returned list with the number of elements calculated above
String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
//lists of length 1 are just the original elements
if(lengthOfList == 1) return elements;
else
{
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);
//append the sublists to each element
int arrayIndex = 0;
for(int i = 0; i < elements.length; i++)
{
for(int j = 0; j < allSublists.length; j++)
{
//add the newly appended combination to the list
allLists[arrayIndex] = elements[i] + allSublists[j];
arrayIndex++;
}
}
return allLists;
}
}此方法不仅会生成所有列表,还会按顺序枚举它们。也就是说,输出将是
aaaa
aaab
aaac
aaa1
aaa2
aaa3
aaba
aabb
aabc
aab1
...
3323
333a
333b
333c
3331
3332
3333使用您的原始输入。它也可以产生任何长度的单词(对此非常小心!只需要长度为8的单词,我就会得到1,679,616种组合!)。
如果方法让您感到困惑(这是一种递归方法,因此有点难以理解),或者如果您想要解决第二个组合问题,请随意提问。此外,这种方法效率有点低,因为它重新计算了所有子列表的组合,因此对于很长的列表来说它不可行。如果你真的想要效率,你可以将已经计算过的元组存储在全局列表中。