LeetCode讲解篇之40. 组合总和 II

文章目录

题目描述

题解思路

按升序排序candidates,然后遍历candidates,目标数减去当前candidates的数,若该结果小于0,因为candidates的元素大于0,所以后续不会再出现让计算结果等于0的情况,所以直接break,如果该结果等于0,将数据加到结果集合中,然后break,若该结果大于0,则将当前candidates的数加入tmp数组,递归调用,调用结束后,删去tmp中添加的当前candidates的数,然后去掉和当前candidates的数重复的数

题解代码

go 复制代码
func combinationSum2(candidates []int, target int) [][]int {
    sort.Ints(candidates)
    res := make([][]int, 0)
    var dfs func([]int, int)
    tmp := []int{}
    dfs = func(candidates []int, target int) {
        n := len(candidates)
        for i := 0; i < n; i++ {
            temp := target - candidates[i]
            if temp < 0 {
                break
            }
            if temp == 0 {
                res = append(res, append([]int{}, append(tmp, candidates[i])...))
                break
            }
            tmp = append(tmp, candidates[i])
            dfs(candidates[i+1:], temp)
            tmp = tmp[:len(tmp)-1]
            for i < n - 1 && candidates[i] == candidates[i+1] {
                i++
            }
        }
    }
    dfs(candidates, target)
    return res
}
相关推荐
Lazyafei14 小时前
滑动窗口:扩张与收缩的动态区间
算法
FRing0315 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
老歌老听老掉牙15 小时前
三个等价答案:遗传算法如何逼近 Branin 函数
c++·算法·ga
是main不是漫15 小时前
【双指针 | LeetCode11 盛最多水的容器】O(n²) 超时,O(n) 封神:这道“装水题“只差一个思路
开发语言·数据结构·c++·算法
geovindu16 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
Navigator_Z17 小时前
LeetCode //C - 1328. Break a Palindrome
c语言·算法·leetcode
电科_银尘18 小时前
【大模型算法与工程 46】vLLM部署入门:模型服务、请求与运行观测
算法·vllm
AskHarries18 小时前
社区运营打法
算法
人间乄惊鸿客1 天前
c++ 右值
c++·算法