LeetCode 90. Subsets II 解题的一种思路
- 描述
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
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],
[]
]
- 思路
这道题和 Subsets I 很像,但主要的不同在于给定的集合中有重复元素,要求生成的子集合不包含重复的。这道题可以继续使用 Subsets I 的插入思想:遍历所有的集合元素,将其添加到已有的集合元素中。但是这道题不能生成同样的子集合,这就需要在生成子集合的时候做额外的逻辑判断,判断是否允许生成子集合。可以观察生成子集合的规律,已给定集合{1,2,2,2}来讲,当遍历到第三个元素2的时候,此时已生成的集合为
[
[],
[1],
[1,2],
[2]
]
这时继续往集合[],[1]中插入元素2,将会导致重复的子集合出现,能够允许插入的集合为[1,2],[2],观察可以知道,允许添加的集合最后面都有元素2,并且只含有1个2。继续遍历,当遍历到第四个元素2的时候,此时已生成的集合为(假如排除了重复生成的集合):
[
[],
[1],
[1,2],
[2],
[1,2,2],
[2,2]
]
可以知道,向所有的集合中继续插入2而不生成重复集合的集合为[1,2,2],[2,2],这种允许加入的集合有这种规律:集合末尾的元素等于即将插入的数,并且重复n次,n为给定集合元素的第n次重复次数,第一次插入2时n=0,第二次插入2时n=1,第三次插入2时n=3。
- 代码(c#)
综上,所有的代码为:
public IList<IList<int>> SubsetsWithDup(int[] nums)
{
nums = nums.OrderBy(x => x).ToArray();//将数组排序
List<IList<int>> result = new List<IList<int>>();
result.Add(new List<int>());
int repeateCount = 0;
for (int i = 0; i < nums.Length; i++)
{
int count = result.Count;
if (i > 0 && nums[i - 1] == nums[i])
{
repeateCount++;//计算前面有几个重复元素,即n
}
else
{
repeateCount = 0;
}
for (int j = 0; j < count; j++)
{
if (AllowInsert(result[j], repeateCount, nums[i]))//判断是否允许插入
{
var list = result[j].ToList();
list.Add(nums[i]);
result.Add(list);
}
}
}
return result;
}
public bool AllowInsert(IList<int> list, int repeateCount, int target)
{
for (int i = list.Count - 1; i >= 0 && repeateCount > 0; i--)
{
if (list[i] != target)
{
return false;
}
repeateCount--;
}
return repeateCount <= 0;
}
- 相关链接:
原题地址:https://leetcode.com/problems/subsets-ii/description/
Subsets I 解题思路:http://blog.csdn.net/qufayudao/article/details/79426021
本文介绍了解决LeetCode 90题——子集 II 的一种方法,该题要求从可能包含重复元素的整数集合中找出所有不重复的子集组合。文章详细解释了一种插入思想的实现方式,并通过示例说明如何避免生成重复子集。

1241

被折叠的 条评论
为什么被折叠?



