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

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],
[]
]

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的做法就不适合。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: