Backtracking - 40. Combination Sum II
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]
]
思路:
与39题不同的是,数组中同一个元素只能在组合中出现一次,这里只需要先对数组排序,就能去重,做法就和39题一样了。
代码:
func combinationSum2(candidates []int, target int) [][]int {
var res [][]int
if candidates == nil || len(candidates) == 0 {
return res
}
sort.Ints(candidates)
dfs(&res, []int{}, candidates, target, 0)
return res
}
func dfs(res *[][]int, temp []int, nums []int, target int, start int) {
if target < 0 {
return
}
if target == 0 {
*res = append(*res, append([]int{}, temp...))
}
for i := start; i < len(nums); i++ {
if i != start && nums[i] == nums[i-1] {
continue
}
temp = append(temp, nums[i]);
dfs(res, temp, nums, target - nums[i], i+1)
temp = temp[:len(temp)-1]
}
}