题解 | #牛棚分组#
牛棚分组
https://www.nowcoder.com/practice/d5740e4dde3740828491236c53737af4
package main
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @param k int整型
* @return int整型二维数组
*/
func combine( n int , k int ) [][]int {
// write code here
res :=make([][]int ,0 )
solution :=make([]int, 0)
backtrack(&res, solution, 1, n, k)
return res
}
func backtrack(res *[][]int ,solution []int,start,n,k int){
if k==0{
temp :=make([]int, len(solution))
copy(temp, solution)
*res=append(*res, temp)
return
}
for i :=start;i<=n;i++{
solution = append(solution, i)
backtrack(res, solution ,i+1, n, k-1)
solution = solution[:len(solution)-1]
}
}
腾讯成长空间 6065人发布
查看11道真题和解析
