LeetCode Online Judge 题目C# 练习 - Subsets II
2012-10-18 22:42
357 查看
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
代码分析:
比Subsets那题多一个start变量,如果后一个元素跟当天这个相同,下次loop前面的时候就不要从头开始,从prev_count(上一次开始插入的位置)开始。当然也有递归的做法,不贴了。Combinatoric的做法就不适合。
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
public static List<List<int>> SubsetsII2(List<int> S) { S.Sort(); List<List<int>> ret = new List<List<int>>(); List<int> empty = new List<int>(); ret.Add(empty); int start = 0; for (int i = 0; i < S.Count; i++) { int prev_count = ret.Count; for (int j = start; j < prev_count; j++) { List<int> temp = new List<int>(ret[j]); temp.Add(S[i]); ret.Add(temp); } if ((i < S.Count - 1) && (S[i + 1] == S[i])) start = prev_count; else start = 0; } return ret; }
代码分析:
比Subsets那题多一个start变量,如果后一个元素跟当天这个相同,下次loop前面的时候就不要从头开始,从prev_count(上一次开始插入的位置)开始。当然也有递归的做法,不贴了。Combinatoric的做法就不适合。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Minimum Window Substring
- LeetCode Online Judge 题目C# 练习 - Remove Element
- LeetCode Online Judge 题目C# 练习 - Count and Say
- LeetCode Online Judge 题目C# 练习 - Decode Way
- LeetCode Online Judge 题目C# 练习 - Plus One
- LeetCode Online Judge 题目C# 练习 - Search Insert Position
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees II
- LeetCode Online Judge 题目C# 练习 - Climbing Stairs
- 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 Paths
- LeetCode Online Judge 题目C# 练习 - Divid Two Integer
- LeetCode Online Judge 题目C# 练习 - Anagrams
- LeetCode Online Judge 题目C# 练习 - Maximal Rectangle
- LeetCode Online Judge 题目C# 练习 - Maximum Subarray
- LeetCode Online Judge 题目C# 练习 - Merge Sorted Array
- LeetCode Online Judge 题目C# 练习 - Valid Number
- LeetCode Online Judge 题目C# 练习 - Same Tree