Leetcode 78. Subsets & 90. Subsets II

题目来源:leetcode

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

思路:http://www.cnblogs.com/felixfang/p/3775712.html

代码:

class Solution {
   public List<List<Integer>> subsets(int[] nums) {
        
        List<List<Integer>> ls=new ArrayList<List<Integer>>();//用来存放结果
        if (nums.length==0)
            return ls;
        ls.add(new ArrayList<Integer>());//初始加入空
        for (int j=0;j<nums.length;j++){
            List<List<Integer>> temp=new ArrayList<>();//存放数组每增加一个元素,结果需要增加的元素
            //增加的元素为;上次所有结果集中,每个list中加入当前数组的数,别忘了在加上结果集中原有的元素
            for(List<Integer> a:ls){
                List<Integer> merge=new ArrayList<Integer>(a);
                merge.add(nums[j]);
                temp.add(merge);
            }
            ls.addAll(temp);
            
            }
        
        return ls;


    }
}
II    
Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

思路:存在重复元素,思路同上,注意先对数组进行排序
class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res=new ArrayList<>();
        int index=1;
        //List<Integer> lin=new ArrayList<>();
        if(nums.length<=0)
            return res;
        res.add(new ArrayList<Integer>());
        Arrays.sort(nums);//先进行排序
        List<Integer> temp1=new ArrayList<>();
                temp1.add(nums[0]);
                res.add(temp1);
            if(nums.length==1){              
                
                return res;
            }
      
                for(int i=1;i<nums.length;i++){
                   List<List<Integer>> temp=new ArrayList<>();//存放本次增加的元素
                    if(nums[i]!=nums[i-1])
                    {   index=res.size();
                        for(List<Integer> ls:res){
                            List<Integer> a=new ArrayList<>(ls);
                            a.add(nums[i]);
                            temp.add(a);
                        }
                    }
                    else{
                        for(int j=index;j<res.size();j++){
                            List<Integer> a=new ArrayList<>(res.get(j));
                            a.add(nums[i]);
                            temp.add(a);
                        }
                            
                        index=res.size();
                    }
                    res.addAll(temp);
        }
        return res;
        
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值