目录
77. 组合
访问量:978

一、简介

题目:组合-77

给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

案例

输入:n = 4, k = 2
输出:[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

二、实现

func combine(n int, k int) [][]int {
    if k == 0 || n == 0{
        return nil
    }

    res := make([][]int, 0)
    doCombine(1, n, k, []int{}, &res)

    return res
}


func doCombine(start, end, dataSum int, curList []int, res *[][]int) {
    if dataSum == 0 {
        c := make([]int, len(curList))
        copy(c, curList)
        *res = append(*res, c)

        return
    }else if dataSum < 0 {
        return 
    }

    for i:= start; i <= end; i++ {
        curList = append(curList, i)
        doCombine(i+1, end, dataSum -1, curList, res)
        curList = curList[:len(curList) -1]
    }
}