40. The combination of the sum of II-LeetCode

Experience: mainly used backtracking and pruning, pruning must take the whole condition think, or else time will be a lot more

Place to go heavy to take note of how deduplication can not set try to do, more elegant.

Try to write compact condition that can be treated in a recursion in a recursive process where, the conditions change

Write a recursive method, and then go to treatment, so that a small amount of code, and elegant.

 1 class Solution {
 2       public List<List<Integer>> combinationSum2(int[] candidates, int target){
 3            LinkedList<List<Integer>> list=new LinkedList<>();
 4             if(candidates==null||candidates.length==0)
 5                 return list;
 6             Arrays.sort(candidates);
 7             rec(0,list,new LinkedList<Integer>(),candidates,target);
 8             return list;
 9         }
10     public void rec(int index,LinkedList<List<Integer>> list,LinkedList<Integer> tmp,int[] candidates,int target)
11        {
12          if(target<0)
13              return;
14          else if(target==0)
15          {        
16              list.add(new LinkedList(tmp));
17              return;
18          }
19          else
20          {
21              for(int i=index;i< candidates.length&&candidates in a [I] <= target ; I ++ ) // This condition can be improved pruning 
// speed
22 is { 23 is IF (I = index && candidates in a [I] == candidates in a [. 1-I! ]) 24 Continue ; 25 tmp.add (candidates in a [I]); 26 is REC (+ I. 1, List, tmp, candidates in a, target- candidates in a [I]); 27 tmp.removeLast (); 28 } 29 } 30 } 31 is }

 

Guess you like

Origin www.cnblogs.com/pc-m/p/10954734.html