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
}
相关推荐
是誰萆微了承諾14 小时前
【golang学习笔记 gin 】1.2 redis 的使用
笔记·学习·golang
ifanatic18 小时前
[每周一更]-(第159期):Go 工程师视角:容器化技术(Docker/Kubernetes)与CI/CD流程的应用场景
docker·golang·kubernetes
张烫麻辣亮。19 小时前
golang-gin包
开发语言·golang·gin
Sally璐璐19 小时前
Go正则表达式实战指南
数据库·mysql·golang
yuluo_YX19 小时前
Go Style 代码风格规范
开发语言·后端·golang
qq_1728055921 小时前
Go 自建库的使用教程与测试
开发语言·后端·golang
共享家95271 天前
优先搜索(DFS)实战
算法·leetcode·深度优先
007php0071 天前
某大厂MySQL面试之SQL注入触点发现与SQLMap测试
数据库·python·sql·mysql·面试·职场和发展·golang
flashlight_hi1 天前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
雨中散步撒哈拉1 天前
13、做中学 | 初一下期 Golang数组与切片
开发语言·后端·golang