1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// @Title: 组合总和 (Combination Sum)
// @Author: 15816537946@163.com
// @Date: 2020-11-14 16:01:00
// @Runtime: 8 ms
// @Memory: 6.4 MB
func combinationSum(candidates []int, target int) [][]int {
	nLen := len(candidates)
	sort.Ints(candidates)
	ans := make([][]int, 0)

	var backtrace func(int, int, []int)
	backtrace = func(idx, sum int, res []int) {
		if sum < 0 {
			return
		}

		if sum == 0 {
			tmp := make([]int, len(res))
			copy(tmp, res)
			ans = append(ans, tmp)
			return
		}

		for i := idx; i < nLen; i++ {
			backtrace(i, sum-candidates[i], append(res, candidates[i]))
		}
	}

	backtrace(0, target, []int{})

	return ans
}