首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Backtracking - 77. Combinations

Backtracking - 77. Combinations

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

77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

思路:

回溯思想中的组合问题系列,题目意思很明确,问你1~n内挑k个数组合起来,有多少种方式。使用dfs求解,一直找到临时结果中有k个数,之后回溯。

代码:

go:

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

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

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

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

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

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