Skip to content

Commit 0e54000

Browse files
committed
add 39
1 parent 0a7a8db commit 0e54000

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

go/backtracking/39/39.组合总和.go

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,10 @@ func combinationSumMy(candidates []int, target int) (res [][]int) {
106106
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
107107
func combinationSum(candidates []int, target int) [][]int {
108108
sort.Ints(candidates)
109-
return dfs(candidates, target)
109+
return dfs(candidates, target, []int{})
110110
}
111111

112-
func dfs(candidates []int, target int) [][]int {
112+
func dfs1(candidates []int, target int) [][]int {
113113
ret := [][]int{}
114114
for i, d := range candidates {
115115
if target-d < 0 {
@@ -118,7 +118,24 @@ func dfs(candidates []int, target int) [][]int {
118118
ret = append(ret, []int{d})
119119
continue
120120
}
121-
for _, v := range dfs(candidates[i:], target-d) {
121+
for _, v := range dfs1(candidates[i:], target-d) {
122+
ret = append(ret, append([]int{d}, v...))
123+
}
124+
}
125+
return ret
126+
}
127+
128+
func dfs(candidates []int, target int, path []int) [][]int {
129+
ret := [][]int{}
130+
for i, d := range candidates {
131+
if target-d < 0 {
132+
break
133+
} else if target-d == 0 {
134+
path = append(path, d)
135+
ret = append(ret, path)
136+
continue
137+
}
138+
for _, v := range dfs(candidates[i:], target-d, path) {
122139
ret = append(ret, append([]int{d}, v...))
123140
}
124141
}

0 commit comments

Comments
 (0)