Golang | Leetcode Golang题解之第40题组合总和II

题目:

题解:

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. 【算法40. 组合总和 II

    2024-04-23 16:22:04       51 阅读
  2. 40. 组合总和 II

    2024-04-23 16:22:04       58 阅读
  3. leetcode 40. 组合总和 II

    2024-04-23 16:22:04       61 阅读
  4. LeetCode40. 组合总和 II

    2024-04-23 16:22:04       61 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 16:22:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 16:22:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 16:22:04       87 阅读
  4. Python语言-面向对象

    2024-04-23 16:22:04       96 阅读

热门阅读

  1. 面试经典-Redis数据库的数据倾斜

    2024-04-23 16:22:04       30 阅读
  2. mysql面试题四(事务)

    2024-04-23 16:22:04       33 阅读
  3. 两套数据库共享存储传递数据

    2024-04-23 16:22:04       25 阅读
  4. 【算法模板】图论基础算法

    2024-04-23 16:22:04       34 阅读
  5. Uni-App 生命周期

    2024-04-23 16:22:04       33 阅读
  6. Vue 动态加载全局样式css(切换ui主题方案)

    2024-04-23 16:22:04       39 阅读
  7. jupyter notebook用不了multiporcessing的问题

    2024-04-23 16:22:04       29 阅读
  8. Centos 7 安装 RocketMQ 5.14(保姆级)

    2024-04-23 16:22:04       34 阅读
  9. 鼠标手辅助器

    2024-04-23 16:22:04       35 阅读