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

猜你喜欢

转载自www.cnblogs.com/pc-m/p/10948879.html