39. Combination Sum #
Problem #
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]
]
Problem Summary #
Given an array candidates with no duplicate elements and a target number target, find all combinations in candidates where the numbers sum to target.
The numbers in candidates can be chosen repeatedly without limitation.
Solution Ideas #
- The problem asks for all combinations whose total sum is sum, and the combinations need to be deduplicated.
- This problem is similar to Problem 47, except that elements can be used repeatedly.
Code #
package leetcode
import "sort"
func combinationSum(candidates []int, target int) [][]int {
if len(candidates) == 0 {
return [][]int{}
}
c, res := []int{}, [][]int{}
sort.Ints(candidates)
findcombinationSum(candidates, target, 0, c, &res)
return res
}
func findcombinationSum(nums []int, target, index int, c []int, res *[][]int) {
if target <= 0 {
if target == 0 {
b := make([]int, len(c))
copy(b, c)
*res = append(*res, b)
}
return
}
for i := index; i < len(nums); i++ {
if nums[i] > target { // This can be optimized by pruning
break
}
c = append(c, nums[i])
findcombinationSum(nums, target-nums[i], i, c, res) // Note that when iterating here, index still remains unchanged, because an element can be chosen multiple times
c = c[:len(c)-1]
}
}