给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例
输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
解法
本题相当于将 78.子集 中的不包含重复元素的约束条件去掉了,所以我们只需在78题基础上完成去重工作即可。
去除由数字相同排列导致的重复,这种重复是由于当前分支还未使用某数字,而同一层的前一个分支已经用到了该数字,于是导致两分支的排列相同。我们先声明一个 bool 数组,表示nums中元素的使用情况,对数组排序后,再用 if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue;
来避免重复。
下面这张图可帮助大家更好的理解
public IList<IList<int>> SubsetsWithDup(int[] nums)
{
IList<IList<int>> res = new List<IList<int>>(){new List<int>()};
Stack<int> stack = new Stack<int>();
bool[] used = new bool[nums.Length];
Array.Sort(nums);
for (int i = 1; i <= nums.Length; i++)
{
BackTrack(res, stack, used, 0, i, nums);
}
return res;
}
public void BackTrack(IList<IList<int>> res, Stack<int> stack, bool[] used, int first, int count, int[] nums)
{
if (stack.Count == count) res.Add(stack.ToArray());
else
{
for (int i = first; i < nums.Length; i++)
{
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;//去除相同排列的重复
used[i] = true;
stack.Push(nums[i]);
BackTrack(res, stack, used, i + 1, count, nums);
stack.Pop();
used[i] = false;
}
}
}