组合总数 II
组合总数 II

https://leetcode.cn/problems/combination-sum-ii/
题解:https://leetcode.cn/problems/combination-sum-ii/solution/dai-ma-sui-xiang-lu-dai-ni-xue-tou-hui-s-ig29/
var ans [][]int //最终结果 var mp map[int]bool //mp[i]标记同一层遍历过程中,candidate[i]这个数是否被重复使用 func combinationSum2(candidates []int, target int) [][]int { mp=make(map[int]bool) sort.Ints(candidates) var tmpAns []int //中间结果 ans=ans[:0] //每个测试样例需要初始化全局变量,否则会测试不通过 dfs(0,0,target,candidates,tmpAns) return ans } func dfs(index,sum,target int,candidates,tmpAns []int){ if sum==target{ //tmp:=tmpAns[:len(tmpAns)] //浅拷贝 tmp:=make([]int,len(tmpAns)) copy(tmp,tmpAns)//拷贝 ans=append(ans,tmp) return } if sum>target{ return } for i:=index;i<len(candidates);i++{ if i>0&&candidates[i]==candidates[i-1]&&mp[i-1]==false{ //mp[i-1]==false,标识在同一层i遍历过程中,当前组合没有重复出现 //假设candidate为[1,1],target=1,那么遍历第一个树的时候组合为[1]已经使用过,然后又取[1],那么就重复了 continue } tmpAns=append(tmpAns,candidates[i]) mp[i]=true sum=sum+candidates[i] dfs(i+1,sum,target,candidates,tmpAns) //回溯 sum=sum-candidates[i] tmpAns=tmpAns[:len(tmpAns)-1] mp[i]=false } }
等风起的那一天,我已准备好一切

浙公网安备 33010602011771号