【发布时间】:2016-06-02 12:44:53
【问题描述】:
我有一个嵌套的List<List<int>> 数据结构,我想遍历最里面的int 元素的每个可能组合,例如在每个组合中,每个内部List<int> 中的一个值被使用。例如,请考虑以下嵌套列表:
var listOfLists = new List<List<int>>()
{
new List<int>() { 1, 2, 3, 4, 9 },
new List<int>() { 0, 3, 4, 5 },
new List<int>() { 1, 6 }
};
前几个组合会产生:
1 0 1 // Indices: 0 0 0
1 0 6 // Indices: 0 0 1
1 3 1 // Indices: 0 1 0
1 3 6 // Indices: 0 1 1
2 0 1 // Indices: 1 0 0
2 0 6 // Indices: 1 0 1
2 3 1 // Indices: 1 1 0
...
我怎样才能做到这一点?
我最初的方法是对索引进行排列,但内部 List<int> 列表的长度不一定相等。我能想到的另一种方法是将每个内部 List<int> 的长度相乘,然后使用模数和除法运算符结合 Math.Floor 来确定索引,但我不确定当 N 集合时如何实现存在。
【问题讨论】:
-
(更正了我的链接)ericlippert.com/2010/06/28/…
-
在我的辩护中考虑到重复,我尝试研究这个问题,但我错过了正确的关键字。