leetCode 90.Subsets II(子集II) 解题思路和方法
2015-07-25 09:54
513 查看
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 =
a solution is:
思路:这一题比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], [] ]
思路:这一题比subsets多一了一道重复,具体代码如下:
public class Solution { boolean[] b; Set<String> set; List<List<Integer>> list; Set<String> set1; public List<List<Integer>> subsetsWithDup(int[] nums) { b = new boolean[nums.length]; set = new HashSet<String>(); list = new ArrayList<List<Integer>>(); set1 = new HashSet<String>(); Arrays.sort(nums); count(nums,"",nums.length,0); return list; } private void count(int[] nums,String s,int n,int j){ //没有重复才添加 if(set.add(s)){ //以","分割数组 String[] sa = s.split(","); List<Integer> al = new ArrayList<Integer>(); for(int i = 0; i < sa.length; i++){ if(sa[i].length() > 0){ al.add(Integer.parseInt(sa[i])); } } Collections.sort(al); if(set1.add(al.toString())) list.add(al); } for(int i = j; i < nums.length;i++){ if(!b[i]){ b[i] = true; count(nums,s + "," + nums[i],n-1,i+1); b[i] = false; } } } }
下面这种写法更简洁:
public class Solution { List<List<Integer>> list;//结果集 List<Integer> al;//每一项 public List<List<Integer>> subsetsWithDup(int[] nums) { list = new ArrayList<List<Integer>>(); al = new ArrayList<Integer>(); Arrays.sort(nums); //排列组合 count(nums,al,0); return list; } private void count(int[] nums,List<Integer> al,int j){ list.add(new ArrayList<Integer>(al));//不重复的才添加 for(int i = j; i < nums.length;i++){ if(i == j || nums[i] != nums[i-1]){//去除重复 al.add(nums[i]);//添加 count(nums,al,i+1); al.remove(al.size()-1);//去除,为下一个结果做准备 } } } }
相关文章推荐
- 使用JS charts来画图表(一)——条形图
- 文化部全面解禁资企业生产销售游戏机
- 洞穴逃生
- 关于《一种鱼眼图象到透视投影图象的变换模型》
- 2015年7月20日 JS第三课(获取时间,数值取值,定时器)
- JQuery如何监听DIV内容变化
- 随笔
- (剑指Offer)面试题31:连续子数组的最大和
- 一种基于非时间逆序的微博优先处理方法
- CLISP special
- 大富翁
- python ,java 变量作用域
- 编写高质量iOS与OS X代码的52个有效方法上
- 网站设计师行业分析
- 6. 菜单切换 - 被选中的底部无线
- javascript笔记06:类的创建
- 毕业后,你变胖了吗?
- hdu 5284 wyh2000 and a string problem(没有算法,只考思维,字符数组得开20万,不然太小了)
- Java 多线程(六) synchronized关键字详解
- leetcode 228 Summary Ranges