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
}
相关推荐
_日拱一卒1 小时前
LeetCode:105从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
ʚ希希ɞ ྀ1 小时前
dp反思与总结
算法·leetcode·动态规划
菜菜的顾清寒1 小时前
力扣Hot100(23)反转链表
算法·leetcode·链表
m0_629494732 小时前
LeetCode 热题 100-----27. 合并两个有序链表
数据结构·算法·leetcode·链表
水木流年追梦2 小时前
大模型入门-RL基础
开发语言·python·算法·leetcode·正则表达式
念何架构之路2 小时前
Go pprof性能剖析
开发语言·后端·golang
人道领域2 小时前
【LeetCode刷题日记】617.合并二叉树(空间换安全,还是原地省内存)
java·数据结构·算法·leetcode
姚不倒2 小时前
Go语言实战:构建一个安全的计算器服务(接口、错误处理与Panic恢复)
云原生·golang
运筹vivo@2 小时前
3043. 最长公共前缀的长度(Leetcode 每日一题)
c++·算法·leetcode·职场和发展·每日一题
csdn_aspnet14 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展