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
}
相关推荐
Dream it possible!12 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊12 小时前
算法之双指针系列(一)
算法·leetcode
Pniubi14 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
Pniubi15 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
联犀15 小时前
纯 Go 的 CAD 开源库 go-cad:直接解析 DWG/DXF,现在也能导出 PDF
开发语言·golang·pdf
FungLeo19 小时前
成为全栈·Go 后端篇·三轮代码审阅之后:把可读性和证据做成工程规则
golang·go·ast·静态检查·成为全栈·代码审阅
文丑颜不良啊20 小时前
LeetCode2081~2100题目解析
java·leetcode
文丑颜不良啊21 小时前
LeetCode2061~2080题目解析
java·leetcode
联犀1 天前
联犀 Go SIMD 实战:视频转码从 16.5ms 到 5.46ms
开发语言·golang·音视频
文丑颜不良啊1 天前
LeetCode1941~1960题目解析
java·leetcode