题目
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
代码
不含重复元素的解法:
http://blog.csdn.net/daigualu/article/details/76348947
与解决不含重复元素的子集思路一致,只有两处不同:
1. 需要对数组排序
2. 过滤重复项
public class Solution {
private IList<IList<int>> rtn = new List<IList<int>>();
public IList<IList<int>> SubsetsWithDup(int[] nums)
{
Array.Sort(nums); //diff1: in-place sort
rtn.Add(new List<int>());
rtn.Add(new List<int>(nums));
dfs2(nums, new List<int>(), 0, 1); //call dfs
return rtn;
}
//assert: ndigts>=1
//dfs: two recursion return conditions for dfs :
//1. size for an item of this subsets increases to ndigits
//2. depth-first-search for nums[i] with ndigits is to the end point.
private void dfs2(int[] nums, IList<int> item, int start, int ndigts)
{
if (ndigts == item.Count)
{
rtn.Add(new List<int>(item));
return; //dfs recursion return condition 1
}
while (ndigts < nums.Length)
{
for (int i = start; i < nums.Length; i++)
{
//diff2: filter duplicates
if (i > start && nums[i] == nums[i - 1])
continue;
item.Add(nums[i]);
dfs2(nums, item, i + 1, ndigts); //forward 1 to search
item.RemoveAt(item.Count - 1);
}
if (item.Count == 0)
ndigts++;
else //dfs recursion return condition 2
return;
}
}
}