LeetCode 39. Combination Sum

Given a set ofcandidate numbers (C(without duplicates) and atarget number (T), find all unique combinations in C wherethe candidate numbers sums to T.

The same repeatednumber may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example,given candidate set [2, 3, 6, 7] andtarget 7
A solution set is: 

[

 [7],

  [2,2, 3]

]

直接回溯:

遍歷數組每個元素:選擇當前元素---》遞歸,不選擇當前元素---》遞歸

再加上累計和(sum)與目標(target)比較判斷

class Solution {
         List<List<Integer>>ans;
         inttarget;
   public List<List<Integer>> combinationSum(int[] candidates,int target) {
       ans = new ArrayList<List<Integer>>();
       this.target = target;
       Arrays.sort(candidates);
       travelCandidates(candidates,0,0,new ArrayList<Integer>());
       return ans;
    }
 
   public void travelCandidates(int[] candidates,int cur,intsum,List<Integer> list){
             if(cur>=candidates.length) return;
 
             travelCandidates(candidates,cur+1,sum,newArrayList<Integer>(list));
 
             sum += candidates[cur];
             list.add(candidates[cur]);
             if(sum == target){ans.add(list);return;}
             if(sum < target){travelCandidates(candidates,cur,sum,list);}
    }
}

 

提交後只超越了5%的提交者…看了下討論模塊,發現自己遞歸優化少(能用循環的就少用遞歸),優化代碼:

public class Solution {
   public List<List<Integer>> combinationSum(int[] candidates,int target) {
             Arrays.sort(candidates);
       List<List<Integer>> result = newArrayList<List<Integer>>();
       getResult(result, new ArrayList<Integer>(), candidates, target,0);
        
       return result;
    }
   
   private void getResult(List<List<Integer>> result,List<Integer> cur, int candidates[], int target, int start){
             if(target > 0){
                       for(int i = start; i <candidates.length && target >= candidates[i]; i++){
                                cur.add(candidates[i]);
                                getResult(result,cur, candidates, target - candidates[i], i);
                                cur.remove(cur.size()- 1);
                       }//for
             }//if
             else if(target == 0 ){
                       result.add(newArrayList<Integer>(cur));
             }//else if
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章