Skip to content

Commit 1587b1f

Browse files
committed
array: 组合
Change-Id: Ic3ad2fba01037db061618e0ebb61a7adc595b43c
1 parent 740bb99 commit 1587b1f

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

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

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,28 @@
4545
* ]
4646
*
4747
*/
48+
49+
// 求所有解的组合一般可以考虑使用递归实现,先往解集合中添加某个元素,递归后如果超过限制则回退,恰好符合则将解加入结果集,若未到达限制则继续尝试添加。
50+
// 由于本题已经限定无重复元素,且元素可以重复选取,那么就是每次先递归同一个元素
51+
func helper(arr []int, target int, start int, out *[]int, res *[][]int) {
52+
if target < 0 {
53+
return
54+
}
55+
if target == 0 {
56+
*res = append(*res, append([]int{}, (*out)...)) // 复制值
57+
return
58+
}
59+
for i := start; i < len(arr); i++ {
60+
*out = append(*out, arr[i])
61+
helper(arr, target-arr[i], i, out, res)
62+
*out = (*out)[:len(*out)-1]
63+
}
64+
}
65+
4866
func combinationSum(candidates []int, target int) [][]int {
49-
67+
out := []int{}
68+
res := [][]int{}
69+
helper(candidates, target, 0, &out, &res)
70+
return res
5071
}
5172

0 commit comments

Comments
 (0)