Skip to content

Commit 64515b1

Browse files
Update 39. 组合总和.md
1 parent 322c541 commit 64515b1

File tree

1 file changed

+54
-2
lines changed

1 file changed

+54
-2
lines changed

Backtrace/39. 组合总和.md

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444

4545
---
4646

47-
回溯 + 剪枝:
47+
**方法一:枚举选哪个**
4848

4949
`target` 开始,每次回溯都减或不减当前下标的值。本题用到剪枝在于先将数组按升序排序,如果当前下标的值小于 `target` 了,那么后续也不需要遍历了。
5050

@@ -73,8 +73,60 @@ class Solution {
7373
backtrace(res, temp, candidates, i, target - candidates[i]);
7474
temp.remove(temp.size() - 1);
7575
}
76+
}
77+
}
78+
```
7679

80+
Go
81+
82+
```go
83+
func combinationSum(candidates []int, target int) [][]int {
84+
res := [][]int{}
85+
var dfs func(index, remain int, temp []int)
86+
dfs = func(index, remain int, temp []int){
87+
if remain == 0 {
88+
res = append(res, slices.Clone(temp)) // 一定要复制一份
89+
return
90+
}
91+
if remain < 0 {
92+
return
93+
}
94+
for i := index; i < len(candidates); i++ {
95+
temp = append(temp, candidates[i])
96+
dfs(i, remain - candidates[i], temp)
97+
temp = temp[:len(temp) - 1]
98+
}
7799
}
100+
dfs(0, target, []int{})
101+
return res
102+
}
103+
```
104+
78105

106+
107+
108+
109+
**方法二:选或不选**
110+
111+
```go
112+
func combinationSum(candidates []int, target int) [][]int {
113+
res := [][]int{}
114+
var dfs func(index, remain int, temp []int)
115+
dfs = func(index, remain int, temp []int){
116+
if index >= len(candidates) || remain < 0 {
117+
return
118+
}
119+
if remain == 0 {
120+
res = append(res, slices.Clone(temp))
121+
return
122+
}
123+
dfs(index + 1, remain, temp)
124+
temp = append(temp, candidates[index])
125+
dfs(index, remain - candidates[index], temp)
126+
temp = temp[:len(temp) - 1]
127+
}
128+
dfs(0, target, []int{})
129+
return res
79130
}
80-
```
131+
```
132+

0 commit comments

Comments
 (0)