LeetCode刷题笔录Subsets II
来源:互联网 发布:网红淘宝店前十名 编辑:程序博客网 时间:2024/05/29 16:19
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], []]比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; }}
0 0
- LeetCode刷题笔录Subsets II
- LeetCode刷题笔录Subsets
- LeetCode刷题笔录 Jump Game II
- LeetCode刷题笔录Single Number II
- LeetCode刷题笔录Unique Paths II
- LeetCode刷题笔录Path Sum II
- LeetCode刷题笔录Word Break II
- LeetCode刷题笔录N-Queens II
- LeetCode刷题笔录Permutations II
- LeetCode刷题笔录Spiral Matrix II
- LeetCode刷题笔录Permutations II
- LeetCode刷题笔录Word Break II
- [leetcode刷题系列]Subsets II
- 【LeetCode】 Subsets Subsets II
- 【LeetCode】Subsets & Subsets II
- LeetCode Subsets && Subsets II
- LeetCode Subsets && Subsets II
- LeetCode-Subsets & Subsets II
- 什么样的外链才算有效性
- 关于运行JAR包中的class
- 如何通过SEO让客户买单
- 关键词选择误区
- 排序算法(三)-- 堆排序
- LeetCode刷题笔录Subsets II
- Swap Nodes in Pairs
- Topcoder SRM 635 Div2 1000 (一种 O(n) 求一棵树中最长连续边 长度的方法)
- 谐振器和振荡器的差异分析
- 使用Batik绘制SVG图并保存为png图像格式
- 15条技巧提高你的写作技巧
- 如何阅读的一点笔记整理
- 【iOS】Swift中扩展extension与协议protocol
- [Leetcode] Generate Parenthesis