生成多个列表的所有组合组合、多个、列表

由网友(守不住的空城)分享简介:由于未知量清单,每一个未知的长度,我需要生成一个独特的名单与所有可能的独特组合。例如,给定以下列表:Given an unknown amount of lists, each with an unknown length, I need to generate a singular list with all p...

由于未知量清单,每一个未知的长度,我需要生成一个独特的名单与所有可能的独特组合。 例如,给定以下列表:

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.

阅读全文

相关推荐

最新文章