leetCode 90.Subsets II(子集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],
  []
]

思路:这一题比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);//去除,为下一个结果做准备
        	}
        }
    }
    
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值