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
}
相关推荐
绿皮的猪猪侠42 分钟前
搜索与图论
算法·深度优先·图论
zx431 小时前
常见的降维算法
笔记·python·算法
WAR|CRANE1 小时前
操作系统面试问题(4)
面试·职场和发展
June`1 小时前
动态规划之背包问题(分割等和子集问题)
算法·动态规划
Felven1 小时前
C. Vlad and a Sum of Sum of Digits
算法
Flower#2 小时前
D. Apple Tree Traversing 【Codeforces Round 1023 (Div. 2)】
c++·算法·图论·dfs
zhangfeng11333 小时前
Matlab 遗传算法的库 gads
算法·数据分析
究极无敌暴龙战神X3 小时前
hot100-子串-JS
javascript·数据结构·算法
codists10 小时前
《算法导论(第4版)》阅读笔记:p14-p16
算法
zilpher_wang10 小时前
K-means
算法·机器学习·kmeans