Leetcode Golang 77. Combinations.go

2019-04-12 11:01:56 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412870

思路

看到这个词,马上就想到了回溯

code

代码语言:javascript复制
func combine(n int, k int) [][]int {
	var res [][]int
	helper(&res, []int{}, 1, n, k)
	return res
}

func helper(res *[][]int, coms []int, start int, n int, k int) {
	if k == 0 {
		tmp := []int{}
		tmp = append(tmp, coms...)
		*res = append(*res, tmp)
		return
	}
	for i := start; i <= n; i   {
		coms = append(coms, i)
		helper(res, coms, i 1, n, k-1)
		coms = coms[:len(coms)-1]
	}
}

0 人点赞