LeetCode-39. Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

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

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

先排序,然后搜索

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> curL = new ArrayList<Integer>();
        Arrays.sort(candidates);
        help(res,curL,candidates,target,target,0);
        return res;
    }
    private void help(List<List<Integer>> re,List<Integer> cur,int[] arr,int target,int value,int index){
        if(value==0){
            List<Integer> l=new ArrayList<>(cur);
            re.add(l);
            return;
        }
        else if(value>0){
            for(int i=index;i<arr.length&&arr[i]<=value;i++){
                cur.add(arr[i]);
                help(re,cur,arr,target,value-arr[i],i);
                cur.remove(cur.size()-1);
            }
        }
    }

 

posted @ 2019-07-18 09:59  月半榨菜  阅读(88)  评论(0编辑  收藏  举报