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
}
相关推荐
8***23558 小时前
【Golang】——Gin 框架中间件详解:从基础到实战
中间件·golang·gin
ヽ格式化12 小时前
Go与PHP变量声明全方位对比:从语法到性能的深度解析
golang·php
CoderYanger13 小时前
递归、搜索与回溯-综合练习:19.目标和
java·算法·leetcode·1024程序员节
ERP老兵-冷溪虎山14 小时前
Python/JS/Go/Java同步学习(第五十篇半)四语言“path路径详解“对照表: 看完这篇定位文件就通透了(附源码/截图/参数表/避坑指南)
java·javascript·python·golang·中医编程·编程四语言同步学·path路径详解
吃着火锅x唱着歌15 小时前
LeetCode 3185.构成整天的下标对数目II
算法·leetcode·职场和发展
资深web全栈开发15 小时前
LeetCode 1590:使数组和能被 p 整除(前缀和 + 哈希表优化)
算法·leetcode·前缀和·算法优化·哈希表·go 语言·取模运算
CoderYanger15 小时前
递归、搜索与回溯-综合练习:27.黄金矿工
java·算法·leetcode·深度优先·1024程序员节
大吱佬15 小时前
GO 八股整理(自用)
开发语言·后端·golang
sin_hielo15 小时前
leetcode 1590
数据结构·算法·leetcode
吃着火锅x唱着歌15 小时前
LeetCode 2748.美丽下标对的数目
数据结构·算法·leetcode