LeetCode 39. Combination Sum

来源:互联网 发布:淘宝搜索结果不对 编辑:程序博客网 时间:2024/06/14 05:01

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

 

原创粉丝点击