您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Combination

2012-07-09 22:12 369 查看
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4]

public static List<List<int>> Combination(int n, int k)
{
List<List<int>>[] ret = new List<List<int>>[2];
ret[0] = new List<List<int>>();
ret[1] = new List<List<int>>();
int new_index = 0;
int curr_index = 0;

for (int i = 1; i <= n; i++)
{
ret[curr_index].Add(new List<int>{ i });
}

for (int i = 2; i <= k; i++)
{
new_index = (curr_index + 1) % 2;

foreach (var item in ret[curr_index])
{
int max = item[item.Count - 1];
for (int j = max + 1; j <= n; j++)
{
item.Add(j);
List<int> temp = new List<int>(item);
ret[new_index].Add(temp);
item.RemoveAt(item.Count - 1);
}
}
ret[curr_index].Clear();
curr_index = new_index;
}

return ret[new_index];
}


代码分析:

  算法很简单,建立两个List<List<int>>集合,往前一个List添加比最后一个元素大的值,存放到新的List中。

  首先往List 1,插入只有一个int的List<int>。

  然后再List 1的基础上,往List 1中的每一个List添加比最后一个元素要大的值. (代码中max 变量存放了LIST最后一个值,最后一个值一定是最大的,然后

for (int j = max + 1; j <= n; j++).
  因为例子中K = 2,所以List 2就是答案,如果K = 3, List 1 就是应该返回的List<List<int>>了。如此类推。

List 1:List 2:List 1:
1;1,2; 1,3; 1,4;1,2,3; 1,3,4;
2;2,3; 2,4;2,3,4;
3;3,4;
4;
  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: