Golang | Leetcode Golang题解之第40题组合总和II

题目:

题解:

Go 复制代码
func combinationSum2(candidates []int, target int) (ans [][]int) {
    sort.Ints(candidates)
    var freq [][2]int
    for _, num := range candidates {
        if freq == nil || num != freq[len(freq)-1][0] {
            freq = append(freq, [2]int{num, 1})
        } else {
            freq[len(freq)-1][1]++
        }
    }

    var sequence []int
    var dfs func(pos, rest int)
    dfs = func(pos, rest int) {
        if rest == 0 {
            ans = append(ans, append([]int(nil), sequence...))
            return
        }
        if pos == len(freq) || rest < freq[pos][0] {
            return
        }

        dfs(pos+1, rest)

        most := min(rest/freq[pos][0], freq[pos][1])
        for i := 1; i <= most; i++ {
            sequence = append(sequence, freq[pos][0])
            dfs(pos+1, rest-i*freq[pos][0])
        }
        sequence = sequence[:len(sequence)-most]
    }
    dfs(0, target)
    return
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}
相关推荐
serendipity_hky1 天前
【go语言 | 第2篇】Go变量声明 + 常用数据类型的使用
开发语言·后端·golang
月明长歌1 天前
【码道初阶】【LeetCode 110】平衡二叉树:如何用一个“Magic Number”将复杂度从O(N²)降为 O(N)?
linux·算法·leetcode
yaoh.wang1 天前
力扣(LeetCode) 14: 最长公共前缀 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
周杰伦_Jay1 天前
【Eino框架】Go语言驱动的LLM应用开发新范式
开发语言·后端·golang
埃伊蟹黄面1 天前
算法 --- hash
数据结构·c++·算法·leetcode
ywwwwwwv1 天前
力扣139
算法·leetcode·职场和发展
黛色正浓1 天前
leetCode-热题100-哈希合集(JavaScript)
javascript·leetcode·哈希算法
2501_941982051 天前
Go 进阶:发送文件/图片消息的流程与实现
开发语言·后端·golang
smj2302_796826521 天前
解决leetcode第3777题使子字符串变交替的最少删除次数
python·算法·leetcode
Tisfy1 天前
LeetCode 2110.股票平滑下跌阶段的数目:数学(一次遍历)
数学·算法·leetcode·题解