mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0040.组合总和II go版本
添加 0040.组合总和II go版本
This commit is contained in:
@ -314,6 +314,48 @@ class Solution:
|
||||
```
|
||||
Go:
|
||||
|
||||
|
||||
> 主要在于如何在回溯中去重
|
||||
|
||||
```go
|
||||
func combinationSum2(candidates []int, target int) [][]int {
|
||||
var trcak []int
|
||||
var res [][]int
|
||||
var history map[int]bool
|
||||
history=make(map[int]bool)
|
||||
sort.Ints(candidates)
|
||||
backtracking(0,0,target,candidates,trcak,&res,history)
|
||||
return res
|
||||
}
|
||||
func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,history map[int]bool){
|
||||
//终止条件
|
||||
if sum==target{
|
||||
tmp:=make([]int,len(trcak))
|
||||
copy(tmp,trcak)//拷贝
|
||||
*res=append(*res,tmp)//放入结果集
|
||||
return
|
||||
}
|
||||
if sum>target{return}
|
||||
//回溯
|
||||
// used[i - 1] == true,说明同一树支candidates[i - 1]使用过
|
||||
// used[i - 1] == false,说明同一树层candidates[i - 1]使用过
|
||||
for i:=startIndex;i<len(candidates);i++{
|
||||
if i>0&&candidates[i]==candidates[i-1]&&history[i-1]==false{
|
||||
continue
|
||||
}
|
||||
//更新路径集合和sum
|
||||
trcak=append(trcak,candidates[i])
|
||||
sum+=candidates[i]
|
||||
history[i]=true
|
||||
//递归
|
||||
backtracking(i+1,sum,target,candidates,trcak,res,history)
|
||||
//回溯
|
||||
trcak=trcak[:len(trcak)-1]
|
||||
sum-=candidates[i]
|
||||
history[i]=false
|
||||
}
|
||||
}
|
||||
```
|
||||
javaScript:
|
||||
|
||||
```js
|
||||
|
Reference in New Issue
Block a user