39. Combination Sum

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

My Solutions:

和combinations类似,把temp加入list的条件是remain == 0。

注意dfs里,dfs到下一步里传送的是i,因为同一个数字可以加入多次

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(candidates); // 这一步可省略
        dfs(list, new ArrayList<Integer>(), candidates, target, 0);
        return list;
    }
    
    public void dfs(List<List<Integer>> list, List<Integer> temp, int[] nums, int remain, int start) {
        if (remain < 0) return;
        if (remain == 0) list.add(new ArrayList<Integer>(temp)); // 满足条件直接返回
        else {
            for (int i = start; i < nums.length; i++){
                temp.add(nums[i]);
                dfs(list, temp, nums, remain - nums[i], i); //i here because one number can be used many times
                temp.remove(temp.size() - 1);
            }
        }
    }
}

Last updated