生成多个列表的所有组合 [英] Generate all combinations from multiple lists
问题描述
由于未知量清单,每一个未知的长度,我需要生成一个独特的名单与所有可能的独特组合。 例如,给定以下列表:
Given an unknown amount of lists, each with an unknown length, I need to generate a singular list with all possible unique combinations. For example, given the following lists:
X: [A, B, C]
Y: [W, X, Y, Z]
然后,我应该能够产生12种组合:
Then I should be able to generate 12 combinations:
[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]
如果添加3个元素的第三列表,我有36种组合,等等。
If a third list of 3 elements were added, I'd have 36 combinations, and so forth.
我如何能够在Java中做到这一点任何想法?
(伪code就可以了太)
Any ideas on how I can do this in Java?
(pseudo code would be fine too)
推荐答案
您需要递归:
假设你所有的名单都在列表
,这是一个列表的列表。让结果是你所需要的排列名单:像这样
Let's say all your lists are in Lists
, which is a list of lists. Let Result be the list of your required permutations: Do it like this
void GeneratePermutations(List<List<Character>> Lists, List<String> result, int depth, String current)
{
if(depth == Lists.size())
{
result.add(current);
return;
}
for(int i = 0; i < Lists.get(depth).size(); ++i)
{
GeneratePermutations(Lists, result, depth + 1, current + Lists.get(depth).get(i));
}
}
最终调用会是这样
The ultimate call will be like this
GeneratePermutations(Lists, Result, 0, EmptyString);
我不知道Java的非常好。上述code是半个C ++,半C#中,有一半的伪code。我倒是AP preciate如果有人可以编辑这个用于Java。
I don't know Java very well. The above code is half C++, half C#, half pseudocode. I'd appreciate if someone could edit this for Java.
这篇关于生成多个列表的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!