LeetCode刷题笔录Subsets II
2014-10-05 04:19
295 查看
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 =
a solution is:
比Subsets要求稍高的一点是这里会出现duplicate elements。想法是如果下一个元素是duplicate,那么在下一次循环中就不是遍历之前所有的solution set,而是只遍历前一次循环中新增加的Solution sets。以[1,2,2]为例:
start: []
itr1: [] [1]
itr2:[] [1] [2] [1,2]
如果itr3按照之前的做法对每个set都加入新的元素2,那么会产生重复:
[] [1] [2] [1,2] [2] [1,2] [1,2,2] [2,2]
可以看到只有[1,2,2]和[2,2]是我们需要新加入的solution set。
因此itr3只应该循环前一次循环新增加的部分
代码如下:
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要求稍高的一点是这里会出现duplicate elements。想法是如果下一个元素是duplicate,那么在下一次循环中就不是遍历之前所有的solution set,而是只遍历前一次循环中新增加的Solution sets。以[1,2,2]为例:
start: []
itr1: [] [1]
itr2:[] [1] [2] [1,2]
如果itr3按照之前的做法对每个set都加入新的元素2,那么会产生重复:
[] [1] [2] [1,2] [2] [1,2] [1,2,2] [2,2]
可以看到只有[1,2,2]和[2,2]是我们需要新加入的solution set。
因此itr3只应该循环前一次循环新增加的部分
代码如下:
public class Solution { public List<List<Integer>> subsetsWithDup(int[] num) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(num == null || num.length == 0) return res; Arrays.sort(num); res.add(new ArrayList<Integer>()); int start = 0; for(int i = 0; i < num.length; i++){ int size = res.size(); for(int j = start; j < size; j++){ List<Integer> sol = new ArrayList<Integer>(res.get(j)); sol.add(num[i]); res.add(sol); } if(i < num.length - 1 && num[i] == num[i + 1]) start = size; else start = 0; } return res; } }
相关文章推荐
- LeetCode刷题笔录Binary Tree Post Order Traversal
- LeetCode 90: Subsets II
- Leetcode: Subsets II
- LeetCode刷题笔录Add Binary
- leetcode90:Subsets II
- leetcode 【 Subsets II 】python 实现
- LeetCode刷题笔录 Binary Tree Preorder Traversal
- LeetCode刷题笔录 Binary Tree Inorder Traversal
- LeetCode刷题笔录Edit Distance
- LeetCode Subsets && Subsets II
- Leetcode: Subsets II
- LeetCode刷题笔录Gas Station
- LeetCode(90) Subsets II
- Leetcode刷题笔录 Anagrams
- LeetCode刷题笔录 Two Sum
- LeetCode刷题笔录Jump Game
- leetcode 刷题之路 57 Subsets II
- leetcode - 90.Subsets II
- Leetcode 90. Subsets II
- Subsets II -- LeetCode