leetcode--Subsets II
2015-06-10 00:25
267 查看
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 =
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums.length==0) return res;
Arrays.sort(nums);
helper(nums, 0, new ArrayList<Integer>(), res);
return res;
}
public void helper(int[] nums, int level, List<Integer> item, List<List<Integer>> res) {
res.add(new ArrayList<Integer>(item));
for(int i=level;i<nums.length;i++){
item.add(nums[i]);
helper(nums,i+1,item,res);
item.remove(item.size()-1);
//跳过相同的元素
while(i<(nums.length-1)&&nums[i]==nums[i+1]) {
i++;
}
}
}
}
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], [] ]
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums.length==0) return res;
Arrays.sort(nums);
helper(nums, 0, new ArrayList<Integer>(), res);
return res;
}
public void helper(int[] nums, int level, List<Integer> item, List<List<Integer>> res) {
res.add(new ArrayList<Integer>(item));
for(int i=level;i<nums.length;i++){
item.add(nums[i]);
helper(nums,i+1,item,res);
item.remove(item.size()-1);
//跳过相同的元素
while(i<(nums.length-1)&&nums[i]==nums[i+1]) {
i++;
}
}
}
}
相关文章推荐
- 杭电 1004
- jQuery中添加自定义或函数方法1
- 这就是搜索引擎--读书笔记八--检索模型与搜索排序
- 精确到秒的JQuery日期控件
- android activity生命周期
- Android开源项目分类汇总
- C++ 画星号图形——空心梯形(核心代码记录)
- 【leetcode c++】09 Palindrome Number
- 将博客搬至CSDN
- Java数据结构-稀疏数组
- 协变返回类型
- 点击button改变div的显示隐藏
- jQuery实现AJAX定时局部页面刷新
- (实验6)二维数组转置 函数调用
- epoll模型的理解封装与应用
- 基于微信公众平台的Python开发——豆瓣电影搜索
- epoll模型的理解封装与应用
- 解决Spinner有时不回调onItemSelected
- C语言指针实现字符串的反转
- 如何在linux环境下安装yaf