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
}
相关推荐
缓风浪起2 分钟前
【力扣】2011. 执行操作后的变量值
算法·leetcode·职场和发展
电子_咸鱼5 小时前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先
仰泳的熊猫5 小时前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
微笑尅乐7 小时前
中点为根——力扣108.讲有序数组转换为二叉搜索树
算法·leetcode·职场和发展
夏鹏今天学习了吗8 小时前
【LeetCode热题100(46/100)】从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
吃着火锅x唱着歌8 小时前
LeetCode 2389.和有限的最长子序列
算法·leetcode·职场和发展
一只鱼^_12 小时前
第 167 场双周赛 / 第 471 场周赛
数据结构·b树·算法·leetcode·深度优先·近邻算法·迭代加深
Dobby_0513 小时前
【Go】C++ 转 Go 第(二)天:变量、常量、函数与init函数
vscode·golang·go
-睡到自然醒~14 小时前
[go 面试] 并发与数据一致性:事务的保障
数据库·面试·golang
科比不来it15 小时前
Go语言数据竞争Data Race 问题怎么检测?怎么解决?
开发语言·c++·golang