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
}
相关推荐
元亓亓亓9 分钟前
LeetCode热题100--136. 只出现一次的数字--简单
算法·leetcode·职场和发展
im_AMBER14 分钟前
Leetcode 113 合并 K 个升序链表
数据结构·学习·算法·leetcode·链表
£漫步 云端彡27 分钟前
Golang学习历程【第十三篇 并发入门:goroutine + channel 基础】
开发语言·学习·golang
TracyCoder12332 分钟前
LeetCode Hot100(22/100)——141. 环形链表
算法·leetcode·链表
重生之后端学习1 小时前
146. LRU 缓存
java·数据结构·算法·leetcode·职场和发展
程曦曦1 小时前
原地删除有序数组重复项:双指针法的艺术与实现
数据结构·算法·leetcode
iAkuya2 小时前
(leetcode)力扣100 60单词搜索(回溯)
算法·leetcode·职场和发展
圣保罗的大教堂2 小时前
leetcode 3637. 三段式数组 I 简单
leetcode
2401_841495642 小时前
【LeetCode刷题】对称二叉树
数据结构·python·算法·leetcode·二叉树··递归
£漫步 云端彡2 小时前
Golang学习历程【第十二篇 错误处理(error)】
开发语言·学习·golang