9.4 subset I and II,


题目详见leetcode

public class Solution {

    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        //http://blog.csdn.net/linhuanmars/article/details/24286377 
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> line = new ArrayList<Integer>();
    if(S==null||S.length==0) return res; 
    Arrays.sort(S); // must have
    res.add(line);
    for(int i=0;i<S.length;i++){
        int size = res.size();
        for(int j=0;j<size;j++){     因为过程中res.size会变, 而第二层loop是为了遍历当前未变化res中的subset集合

            //ArrayList<Integer> tmp = res.get(j);
            ArrayList<Integer> tmp = new ArrayList<Integer>(res.get(j)); 
            tmp.add(S[i]);
            res.add(tmp);
        }
    }
    
    return res;
    }}

 



public class Solution {
    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
        
    
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
           if(num==null||num.length==0) return res;
    res.add(new ArrayList<Integer>());
    Arrays.sort(num);  
    int start =0;
    for(int i=0; i < num.length;i++){
        int size =res.size(); 
        
    //    for(int j=0;j<size();j++){// !!!!!
            for(int j=start;j<size;j++){
            ArrayList<Integer> tmp = new ArrayList<Integer>(res.get(j)); 
            tmp.add(num[i]);
            res.add(tmp);
        }
        if(i<num.length-1&&num[i]==num[i+1]){
            start=size;              // 跳过已经重复元素加过的member!!!!
        }else{start=0;}
    }
    return res;
    
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值