|
44 | 44 |
|
45 | 45 | ---
|
46 | 46 |
|
47 |
| -回溯 + 剪枝: |
| 47 | +**方法一:枚举选哪个** |
48 | 48 |
|
49 | 49 | 从 `target` 开始,每次回溯都减或不减当前下标的值。本题用到剪枝在于先将数组按升序排序,如果当前下标的值小于 `target` 了,那么后续也不需要遍历了。
|
50 | 50 |
|
@@ -73,8 +73,60 @@ class Solution {
|
73 | 73 | backtrace(res, temp, candidates, i, target - candidates[i]);
|
74 | 74 | temp.remove(temp.size() - 1);
|
75 | 75 | }
|
| 76 | + } |
| 77 | +} |
| 78 | +``` |
76 | 79 |
|
| 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 | + } |
77 | 99 | }
|
| 100 | + dfs(0, target, []int{}) |
| 101 | + return res |
| 102 | +} |
| 103 | +``` |
| 104 | + |
78 | 105 |
|
| 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 |
79 | 130 | }
|
80 |
| -``` |
| 131 | +``` |
| 132 | + |
0 commit comments