首页 > 其他 > 详细

39. 组合总和 -LeetCode

时间:2019-05-30 12:29:43      阅读:112      评论:0      收藏:0      [点我收藏+]

技术分享图片

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

都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);
               }
           }
       }
}

 

39. 组合总和 -LeetCode

原文:https://www.cnblogs.com/pc-m/p/10948879.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!