duanlan5320 2018-09-20 11:43
浏览 81

Golang递归和关闭

I can't get what is going on on the following code in function findCombis. The outer scope variable out [][]int looses its contents when data is appended, as shows the print out. Any suggestions why is this happening?

Thanks

package main

import  "fmt"

func main() {
    arr := []int{1, 3, 5, 7, 9}
    comb := findCombis(arr, len(arr), 4)
    fmt.Printf("%v
", 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
", data)
            out = append(out, data)
            fmt.Printf("OUT: %v
", 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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度