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
}
相关推荐
爱coding的橙子9 分钟前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光11 分钟前
leetcode sql50题
算法·leetcode·职场和发展
pay顿12 分钟前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
精神小伙mqpm14 分钟前
leetcode78. 子集
算法·深度优先
岁忧14 分钟前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
Tisfy16 分钟前
LeetCode 2434.使用机器人打印字典序最小的字符串:贪心(栈)——清晰题解
leetcode·机器人·字符串·题解·贪心·
dying_man17 分钟前
LeetCode--18.四数之和
算法·leetcode
知识漫步43 分钟前
代码随想录算法训练营第60期第五十九天打卡
算法
分形数据1 小时前
在Mathematica中实现Newton-Raphson迭代的收敛时间算法(一般三次多项式)
算法·mathematica·复分析
鑫鑫向栄1 小时前
[蓝桥杯]解谜游戏
数据结构·c++·算法·职场和发展·蓝桥杯