40. Combination Sum II

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

Each number in candidates may only be used once in the combination.

Note:

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

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

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

backtracking

和I不同的地方是数组里可以有重复元素,要注意去重

去重:1. 用set; 2. 判断同一个元素是否在同一递归深度出现

s = target / min(nums[i]), T = C(s, 1) + C(s, 2) + ... + C(s, s) = 2^s  -> O(2^s)

time: O(2^s), space: O( target / min(nums[i]) )

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        backtracking(candidates, target, 0, new ArrayList<>(), res);
        return res;
    }
    
    private void backtracking(int[] candidates, int target, int idx, List<Integer> tmp, List<List<Integer>> res) {
        if(target == 0) res.add(new ArrayList<>(tmp));
        
        for(int i = idx; i < candidates.length; i++) {
            if(candidates[i] > target) break;
            if(i > idx && candidates[i] == candidates[i-1]) continue;
            tmp.add(candidates[i]);
            backtracking(candidates, target - candidates[i], i + 1, tmp, res);
            tmp.remove(tmp.size() - 1);
        }
    }
}
原文地址:https://www.cnblogs.com/fatttcat/p/10078100.html