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
}
相关推荐
superior tigre14 小时前
78 子集
算法·leetcode·深度优先·回溯
superior tigre16 小时前
739 每日温度
算法·leetcode·职场和发展
6Hzlia16 小时前
【Hot 100 刷题计划】 LeetCode 15. 三数之和 | C++ 排序+双指针
c++·算法·leetcode
北顾笙98018 小时前
day37-数据结构力扣
数据结构·算法·leetcode
止语Lab18 小时前
Gin 很好,但你的项目可能需要更多
golang·gin
hopetomorrow20 小时前
学习路之go --go入门
golang
6Hzlia20 小时前
【Hot 100 刷题计划】 LeetCode 189. 轮转数组 | C++ 三次反转经典魔法 (O(1) 空间)
c++·算法·leetcode
KeyonY20 小时前
车联网规则引擎设计之热更新与版本管理
redis·golang·车联网
咬_咬21 小时前
go语言学习(函数)
开发语言·学习·golang
m0_6294947321 小时前
LeetCode 热题 100-----13.最大子数组和
数据结构·算法·leetcode