文章目录
- 题目描述
- 题解思路
- 题解代码
题目描述
题解思路
遍历nums,让当前数字添加到结果前缀中,递归调用,直到前缀的长度为k,然后将前缀添加到结果集
题解代码
func combine(n int, k int) [][]int {
var nums = make([]int, n)
for i := n; i > 0; i-- {
nums[i-1] = i
}
var res = make([][]int, 0)
var dfs func(prefix []int, nums []int, k int)
dfs = func(prefix []int, nums []int, k int) {
if k == 0 {
tmp := make([]int, len(prefix))
copy(tmp[:], prefix[:])
res = append(res, tmp)
return
}
for i := 0; i <= len(nums) - k; i++ {
dfs(append(prefix, nums[i]), nums[i+1:], k-1)
}
}
dfs(make([]int, 0, k), nums, k)
return res
}