39. 组合总和 -LeetCode

心得:尽量把不符合的条件过滤,然后进行回溯,以前用的是每次递归

都new一个链表,其实应该把一个链表传进去进行回溯。

代码:

class Solution {
     public List<List<Integer>> combinationSum(int[] candidates, int target) {
           LinkedList<List<Integer>> list=new LinkedList<>();
            if(candidates==null||candidates.length==0)
                return list;
         Arrays.sort(candidates);
            rec(0,list,new LinkedList<Integer>(),candidates,target);
            return list;
        }
    public void rec(int index,LinkedList<List<Integer>> list,LinkedList<Integer> tmp,int[] candidates,int target)
       {
           for(int i=index;i<candidates.length;i++)//这里从index开始,因为index以前的都是重复的
           {
               if(target-candidates[i]<0)
               {
                   return ;//return还是continue想清楚。
               }
               else if(target-candidates[i]>0)
               {
                
                   tmp.add(candidates[i]);
                   rec(i,list,tmp,candidates,target-candidates[i]);
                  tmp.removeLast();
               }
               else
               {
                   tmp.add(candidates[i]);
                   LinkedList<Integer> b=new LinkedList<>(tmp);
                   tmp.removeLast();
                  list.add(b);
               }
           }
       }
}

 

转载于:https://www.cnblogs.com/pc-m/p/10948879.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值