列表排列(数目不详) [英] Lists permutations (unknown number)

查看:120
本文介绍了列表排列(数目不详)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  清单<名单,LT的组合INT>>

我有多个列表,可能是2或3多达10个名单,有多个
值在其中。现在我需要做的就是让所有的组合
其中的

I have multiple Lists, could be 2 or 3 up to 10 lists, with multiple values in them. Now what I need to do is to get a combination of all of them.

例如,如果我有3列出具有以下值:

For example, if I have 3 lists with the following values:


  • 列表1:3,5,7

  • 列表2:3,5,6

  • 清单3:2,9

我会得到这些组合


  • 3,3,2

  • 3,3,9

  • 3,5,2
    等等。

现在的问题是我无法做到这一点很容易,因为我不知道有多少名单我有,因此在确定有多少循环所需要的。

Now the problem is I cannot do this easily because I do not know how many lists I have, therefore determine how many loops I need.

推荐答案

您也许可以作出这样的轻松了很多,但是这是我脑子里刚才:

You could probably make that a lot easier, but this is what I had in mind just now:

List<List<int>> lists = new List<List<int>>();
lists.Add(new List<int>(new int[] { 3, 5, 7 }));
lists.Add(new List<int>(new int[] { 3, 5, 6 }));
lists.Add(new List<int>(new int[] { 2, 9 }));

int listCount = lists.Count;
List<int> indexes = new List<int>();
for (int i = 0; i < listCount; i++)
    indexes.Add(0);

while (true)
{
    // construct values
    int[] values = new int[listCount];
    for (int i = 0; i < listCount; i++)
        values[i] = lists[i][indexes[i]];

    Console.WriteLine(string.Join(" ", values));

    // increment indexes
    int incrementIndex = listCount - 1;
    while (incrementIndex >= 0 && ++indexes[incrementIndex] >= lists[incrementIndex].Count)
    {
        indexes[incrementIndex] = 0;
        incrementIndex--;
    }

    // break condition
    if (incrementIndex < 0)
        break;
}

如果我不是完全错误的,这应该是 0(NM) M 是数列表和 N 排列数(所有 M 列表的长度的产品)。

If I’m not completely wrong, this should be O(Nm) with m being the number of lists and N the number of permutations (product of the lengths of all m lists).

这篇关于列表排列(数目不详)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆