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