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]
代码分析:
算法很简单,建立两个List<List<int>>集合,往前一个List添加比最后一个元素大的值,存放到新的List中。
首先往List 1,插入只有一个int的List<int>。
然后再List 1的基础上,往List 1中的每一个List添加比最后一个元素要大的值. (代码中max 变量存放了LIST最后一个值,最后一个值一定是最大的,然后
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; |
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - 3SUM Closest
- LeetCode Online Judge 题目C# 练习 - Anagrams
- LeetCode Online Judge 题目C# 练习 - N-Queens
- LeetCode Online Judge 题目C# 练习 - Binary Tree Level Order Traversal II
- LeetCode Online Judge 题目C# 练习 - Count and Say
- LeetCode Online Judge 题目C# 练习 - Length of Last Word
- LeetCode Online Judge 题目C# 练习 - Decode Way
- LeetCode Online Judge 题目C# 练习 - Minimum Window Substring
- LeetCode Online Judge 题目C# 练习 - Remove Element
- LeetCode Online Judge 题目C# 练习 - Two Sum
- LeetCode Online Judge 题目C# 练习 - Combination Sum
- LeetCode Online Judge 题目C# 练习 - Divid Two Integer
- LeetCode Online Judge 题目C# 练习 - Plus One
- LeetCode Online Judge 题目C# 练习 - Search Insert Position
- LeetCode Online Judge 题目C# 练习 - Median of Two Sorted Arrays
- LeetCode Online Judge 题目C# 练习 - Merge k Sorted Lists
- LeetCode Online Judge 题目C# 练习 - Pow(x, n)
- LeetCode Online Judge 题目C# 练习 - Set Matrix Zeroes
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees II
- LeetCode Online Judge 题目C# 练习 - Maximal Rectangle