mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加 0039.组合总和 go版本
添加 0039.组合总和 go版本
This commit is contained in:
@ -286,6 +286,39 @@ class Solution:
|
|||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
|
||||||
|
> 主要在于递归中传递下一个数字
|
||||||
|
|
||||||
|
```go
|
||||||
|
func combinationSum(candidates []int, target int) [][]int {
|
||||||
|
var trcak []int
|
||||||
|
var res [][]int
|
||||||
|
backtracking(0,0,target,candidates,trcak,&res)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int){
|
||||||
|
//终止条件
|
||||||
|
if sum==target{
|
||||||
|
tmp:=make([]int,len(trcak))
|
||||||
|
copy(tmp,trcak)//拷贝
|
||||||
|
*res=append(*res,tmp)//放入结果集
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if sum>target{return}
|
||||||
|
//回溯
|
||||||
|
for i:=startIndex;i<len(candidates);i++{
|
||||||
|
//更新路径集合和sum
|
||||||
|
trcak=append(trcak,candidates[i])
|
||||||
|
sum+=candidates[i]
|
||||||
|
//递归
|
||||||
|
backtracking(i,sum,target,candidates,trcak,res)
|
||||||
|
//回溯
|
||||||
|
trcak=trcak[:len(trcak)-1]
|
||||||
|
sum-=candidates[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
```
|
||||||
JavaScript:
|
JavaScript:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
Reference in New Issue
Block a user