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
}
相关推荐
偷吃的耗子7 分钟前
【CNN算法理解】:CNN平移不变性详解:数学原理与实例
人工智能·算法·cnn
dazzle1 小时前
机器学习算法原理与实践-入门(三):使用数学方法实现KNN
人工智能·算法·机器学习
那个村的李富贵1 小时前
智能炼金术:CANN加速的新材料AI设计系统
人工智能·算法·aigc·cann
张张努力变强1 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发1 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
张登杰踩1 小时前
MCR ALS 多元曲线分辨算法详解
算法
YuTaoShao2 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波0072 小时前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
HY小宝F2 小时前
职场沟通的深层智慧:从对抗到协作的自我修炼
职场和发展
风暴之零2 小时前
变点检测算法PELT
算法