Subsets II
来源:互联网 发布:远程协助软件steam 编辑:程序博客网 时间:2024/06/05 02:24
题目:
https://leetcode.com/problems/subsets-ii/
Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], []]分析:
求子集,且子集元素从小到大排列,且不能有重复的
参考代码如下:
http://www.programcreek.com/2013/01/leetcode-subsets-ii-java/
从后往前挨个遍历,每次如果不是第一次,而且当前元素不等于前一个元素,获取当前结果集中的list列表prev,
将当前元素加到每个list的第一位;
如果当前元素跟前一个元素不相同,则把此单元素加入到prev当中
最后将此轮得到的新元素集合加入到结果集中!
public class Solution { public List<List<Integer>> subsetsWithDup(int[] num) {if (num == null)return null; Arrays.sort(num); List<List<Integer>> result = new ArrayList<List<Integer>>();List<List<Integer>> prev = new ArrayList<List<Integer>>(); for (int i = num.length-1; i >= 0; i--) { //get existing setsif (i == num.length - 1 || num[i] != num[i + 1] || prev.size() == 0) {prev = new ArrayList<List<Integer>>();for (int j = 0; j < result.size(); j++) {prev.add(new ArrayList<Integer>(result.get(j)));}} //add current number to each element of the setfor (List<Integer> temp : prev) {temp.add(0, num[i]);} //add each single number as a set, only if current element is different with previousif (i == num.length - 1 || num[i] != num[i + 1]) {ArrayList<Integer> temp = new ArrayList<Integer>();temp.add(num[i]);prev.add(temp);} //add all set created in this iterationfor (List<Integer> temp : prev) {result.add(new ArrayList<Integer>(temp));}} //add empty setresult.add(new ArrayList<Integer>()); return result; }}
0 0
- 【LeetCode】 Subsets Subsets II
- 【LeetCode】Subsets & Subsets II
- LeetCode Subsets && Subsets II
- Subsets and Subsets II
- LeetCode Subsets && Subsets II
- LeetCode-Subsets & Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- Subsets II
- JAVA阶段以及收银系统项目总结
- Android初中级阶段——一个新的开始,新的起点
- 查询与20号部门某个员工工资相等的员工信息
- 不到两年时间,半导体界发生了如此多收购兼并案---ESM
- 包装类、字符串方法、时间处理、正则表达式
- Subsets II
- Git 分支管理策略
- HTTPCLIENT MultipartEntity 上传中文乱码
- HDOJ 1753 大明A+B (高精度的小数加法 java )
- 用顺序表求lc=la-lb
- 年终总结之那些年,我们提高的思想
- C++关于引用的说明
- Hudson 的安装和使用
- js事件委托