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
}
相关推荐
leonkay7 小时前
Golang语言闭包完全指南
开发语言·数据结构·后端·算法·架构·golang
IronMurphy10 小时前
【算法二十六】108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
数据结构·算法·leetcode
im_AMBER11 小时前
Leetcode 141 最长公共前缀 | 罗马数字转整数
算法·leetcode
WolfGang00732111 小时前
代码随想录算法训练营 Day13 | 二叉树 part03
数据结构·算法·leetcode
一叶落43812 小时前
167. 两数之和 II - 输入有序数组【C语言题解】
c语言·数据结构·算法·leetcode
echome88813 小时前
Go 语言并发编程实战:用 Goroutine 和 Channel 构建高性能任务调度器
开发语言·后端·golang
一叶落43813 小时前
LeetCode 54. 螺旋矩阵(C语言详解)——模拟 + 四边界收缩
java·c语言·数据结构·算法·leetcode·矩阵
王老师青少年编程14 小时前
2026年3月GESP真题及题解(C++二级):数数
c++·题解·真题·gesp·数数·二级·2026年3月
Storynone14 小时前
【Day27】LeetCode:56. 合并区间,738. 单调递增的数字
python·算法·leetcode
计算机安禾14 小时前
【C语言程序设计】第31篇:指针与函数
c语言·开发语言·数据结构·c++·算法·leetcode·visual studio