leetcode 40. Combination Sum II

leetcode 40. Combination Sum II

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
A solution set is: 

[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6]]

题解:结果中不能包含重复的数组;

解法1:

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(candidates);
        combination(candidates,target,res,list,0);
        return res;
    }
    
   public void combination(int[] candidates,int target,List<List<Integer>> res,List<Integer> list,int index){
        for(int i=index;i<candidates.length;i++){
            if(candidates[i] == target){
                List<Integer> tmp = new ArrayList<Integer>(list); //或tmp.addAll(list);
                tmp.add(candidates[i]);
                if(!res.contains(tmp)){
                    res.add(tmp);
                }
                
            }else if(candidates[i] < target){
                List<Integer> tmp = new ArrayList<Integer>(list); //不能直接list.add(candidates[i]),然后将list向下传递
                tmp.add(candidates[i]);
                combination(candidates,target-candidates[i],res,tmp,i+1);
            }else{
                break;
            }
        }
    }
   
   

解法2:

leetcode上未通过,超时

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(candidates);
        for(int i=1;i<=candidates.length;i++){
       combine(candidates,0,list,res,i,target);
   }
        
        return res;
    }
   
   public void combine(int []cs,int begin,List<Integer> list,List<List<Integer>> res,int num,int target){ 
    if(num == 0){
       List<Integer> tmp = new ArrayList<Integer>(list);
       if(target == 0 && !res.contains(tmp)){ //不能通过res.contains(list)判断元素是否重复,因为list的地址是不变的,判断一直为真
          res.add(tmp); //不能res.add(list),list地址是不变的,且初始list为空,这样做的结果是 res最终也为空
       }
    return;
    }
    if(begin == cs.length) return;
    list.add(cs[begin]);
    combine(cs,begin+1,list,res,num-1,target-cs[begin]);
       list.remove(list.size() -1);
       combine(cs,begin+1,list,res,num,target);
   }  



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值