30 lines
671 B
Go
30 lines
671 B
Go
package q39
|
|
|
|
import "slices"
|
|
|
|
func mkCombs(candidates []int, target int, buf []int, ret [][]int) [][]int {
|
|
if target == 0 {
|
|
cp := make([]int, len(buf))
|
|
copy(cp, buf)
|
|
return append(ret, buf)
|
|
}
|
|
if len(candidates) == 0 || candidates[0] > target {
|
|
return ret
|
|
}
|
|
for i := 0; candidates[0]*i <= target; i++ {
|
|
ret = mkCombs(candidates[1:], target-i*candidates[0], buf, ret)
|
|
buf = append(buf, candidates[0])
|
|
}
|
|
return ret
|
|
}
|
|
|
|
func combinationSum(candidates []int, target int) [][]int {
|
|
slices.Sort(candidates)
|
|
|
|
ret := make([][]int, 0, 150)
|
|
buf := make([]int, target/candidates[0]+1)
|
|
|
|
return mkCombs(candidates, target, buf[:0], ret)
|
|
}
|
|
|
|
var _ = combinationSum
|