前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Backtracking - 216. Combination Sum III

Backtracking - 216. Combination Sum III

作者头像
ppxai
发布2020-09-23 17:33:08
1600
发布2020-09-23 17:33:08
举报
文章被收录于专栏:皮皮星球

216. Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

  • All numbers will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

代码语言:javascript
复制
Input: k = 3, n = 7
Output: [[1,2,4]]

Example 2:

代码语言:javascript
复制
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

思路:

这一题是组合系列的变形题,要求用k个1-9的数组组合出n值,采用回溯来做,使用组合的个数为k个和为n来剪枝。

代码:

代码语言:javascript
复制
func combinationSum3(k int, n int) [][]int {

    var res [][]int
    dfs(1, k, n, 0, []int{}, &res)
    return res
}

func dfs(start, k, n, sum int, temp []int, res *[][]int) {
    if sum == n && k == 0 {
        *res = append(*res, append([]int{}, temp...))
        return
    }
    if k == 0 {
        return 
    }
    
    for i := start; i <= 9; i++ {
        temp = append(temp, i)
        dfs(i+1, k-1, n, sum + i, temp, res)
        temp = temp[:len(temp)-1]
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年09月03日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档