Golang递归和关闭

时间:2018-09-20 11:43:20

标签: go

我无法获得函数 findCombis 中以下代码的作用。附加数据时,外部作用域变量out [][]int释放其内容,如打印输出所示。有什么建议为什么会发生这种情况?

谢谢

package main

import  "fmt"

func main() {
    arr := []int{1, 3, 5, 7, 9}
    comb := findCombis(arr, len(arr), 4)
    fmt.Printf("%v\n", comb)
}

func findCombis(arr []int, n int, m int) [][]int {
    // define an array tthat will hold the arrays of combinations
    out := [][]int{}
    // define temporary array to hold currect combination
    data := make([]int, m)
    // define a func variable to use anonymous function with recursion
    var combinationUtil func(arr []int, data []int, start, end, idx, m int)

    // recursive function
    combinationUtil = func(arr []int, data []int, start int, end int, idx int, m int) {
        // current combination is ready store it
        if idx == m {
            fmt.Printf("DATA: %v\n", data)
            out = append(out, data)
            fmt.Printf("OUT: %v\n", out)
            return
        }
        //  replace index with all possible elements.
        for i := start; i <= end && end-i+1 >= m-idx; i++ {
            data[idx] = arr[i]
            combinationUtil(arr, data, i+1, end, idx+1, m)
        }
    }
    combinationUtil(arr, data, 0, n-1, 0, m)
    return out
}

0 个答案:

没有答案