Backtracking - 77. Combinations

时间:2022-07-25
本文章向大家介绍Backtracking - 77. Combinations,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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]
    }
}