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]
]
class Solution {
public List<List<Integer>> combinationSum(int[] nums, int target) {
    List<List<Integer>> list = new ArrayList<>();
    backtrack(list, new ArrayList<>(), nums, target, 0);
    return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
    if(remain < 0) return;
    else if(remain == 0) list.add(new ArrayList<>(tempList));
    else{ 
        for(int i = start; i < nums.length; i++){
            tempList.add(nums[i]);
            backtrack(list, tempList, nums, remain - nums[i], i); 
            //找到了一个解或者 remain < 0 了,将当前数字移除,然后继续尝试
            tempList.remove(tempList.size() - 1);
        }
    }
}

}

大佬给的答案是回溯法,和我想的一样,但是我只想出了个大概,用code写不出我的想法,所以还要多练。

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList();
        help(res, new ArrayList(), 0, candidates, target, 0);
        return res;
    }
    
    public void help(List<List<Integer>> res, List<Integer> cur, int count, int[] candidates, int target, int start) {
        if(count > target) return;
        if(count == target) {
            res.add(new ArrayList(cur));
            return;
        }
        
        for(int i = start; i < candidates.length; i++) {
            count += candidates[i];
            cur.add(candidates[i]);
            help(res, cur, count, candidates, target, i);
            count -= candidates[i];
            cur.remove(cur.size() - 1);
        }
    }
}

如何保证只产生2,2,3不会有3,2,2?还是需要start这个变量,start把i传过去,i就只会从自己start或后面的元素选,如果i从0开始就会一直有重复。

posted @ 2019-02-07 03:38  Schwifty  阅读(111)  评论(0编辑  收藏  举报