GoLang刷题之leetcode

本文介绍了如何解决LeetCode题目40,即在给定候选数数组和目标数的情况下,找出所有和为目标数且不包含重复组合的算法。关键点在于对候选数组进行升序排序并利用递归方法处理去重问题。
摘要由CSDN通过智能技术生成

题目40:组合总和Ⅱ

题目描述:

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次 。

注意:解集不能包含重复的组合。

题解:

这题与39题的区别在于如何去重,对candidates进行升序排序,相同的数必定相连,直接跳过就行

func combinationSum2(candidates []int, target int) [][]int {
    res, r := [][]int{}, []int{}
    if len(candidates)==0{
        return res
    }
    sort.Ints(candidates) 
    helper(candidates, target, 0, r, &res)
    return res
}
func helper(candidates []int, target int, n int, r []int, res *[][]int){
    if target==0{
        c := make([]int, len(r))
        copy(c, r)
        *res = append(*res, c)
        return
    }
    for i:=n;i<len(candidates);i++{
        if i>n&&candidates[i]==candidates[i-1]{
            continue
        }
        if target >= candidates[i]{
            r = append(r, candidates[i])
            helper(candidates, target-candidates[i],i+1,r, res)
            r = r[:len(r)-1]
        }
    }
}
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值