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
}
相关推荐
Nil20820 分钟前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2081 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
tachibana21 小时前
Go 语言里的 Context 是什么?
开发语言·后端·golang·go·语言
lvwangshu2 小时前
川剧复演 题解
动态规划·题解·技巧·性质题·思维好题
局部有解6 小时前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil2088 小时前
leetcode 75颜色分类
数据结构·算法·leetcode
茉莉玫瑰花茶8 小时前
GO [ 数据格式 ]
服务器·网络·算法·golang
aqiu1111118 小时前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表
不会就选b9 小时前
算法日常・每日刷题--<动态规划>29
数据结构·算法·leetcode
土豆.exe9 小时前
chunked 编码的行尾:Go、h11 与 Tomcat 各错在哪一处
开发语言·网络安全·golang·tomcat