-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcombination-sum.go
76 lines (53 loc) · 1.32 KB
/
combination-sum.go
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package array
import (
"fmt"
"sort"
)
func combinationSum(candidates []int, target int) [][]int {
l := len(candidates)
res := [][]int{}
path := []int{}
combinationRecursion(candidates, l, target, 0, path, &res)
res2 := [][]int{}
path2 := []int{}
sort.Ints(candidates)
combinationRecursion2(candidates, l, target, 0, path2, &res2)
fmt.Println("======", res, res2)
return res
}
func combinationRecursion(nums []int, l, target, start int, path []int, res *[][]int) {
// 终止条件
if target < 0 {
return
}
// 结果满足
if target == 0 {
*res = append(*res, append([]int{}, path...))
return
}
for i := start; i < l; i++ {
path = append(path, nums[i])
// 递归阶段
fmt.Println("=====>递归前", path)
combinationRecursion(nums, l, target-nums[i], i, path, res)
// 回溯
path = path[0 : len(path)-1]
fmt.Println("=====>递归后", path)
}
}
func combinationRecursion2(nums []int, l, target, start int, path []int, res *[][]int) {
if target == 0 {
*res = append(*res, append([]int{}, path...))
return
}
for i := start; i < l; i++ {
if target-nums[i] < 0 {
break
}
path = append(path, nums[i])
fmt.Println("=====>递归前", path)
combinationRecursionUnique(nums, l, target-nums[i], i, path, res)
path = path[0 : len(path)-1]
fmt.Println("=====>递归后", path)
}
}