doom910730 2017-11-03 11:23
浏览 51
已采纳

如何在GO中的切片中存储递归获得的组合?

Combinations can be printed using the following recursive code (inspired from Rosetta)

I thought it would be easy to store the intermediate results in an []int or the set of combination in an [][]int. But, because the function is recursive, it is not so easy than replacing the

fmt.Println(s)

by a

return s

with a minor modification of the function output for example. I also tried to feed a pointer like

p *[][]int

with the variable "s" inside the recursive function, but I failed :-/

I think it is a general problem with recursive functions so if you have some advises to solve this problem it will help me a lot !

Many thanks in advance ! ;)

package main

import (
    "fmt"
)

func main() {

    comb(5, 3)
}

func comb(n, m int) {

    s := make([]int, m)
    last := m - 1
    var rc func(int, int)
    rc = func(i, next int) {
        for j := next; j < n; j++ {
            s[i] = j
            if i == last {
                fmt.Println(s)  
            } else {
                rc(i+1, j+1)
            }
        }
        return 
    }
    rc(0, 0)
}
  • 写回答

1条回答 默认 最新

  • douju2331 2017-11-03 11:43
    关注

    Seems to me that s is being reused by each rc call so you just need to ensure that when storing s into an [][]int you store its copy, so as to not overwrite its contents during the next iteration.

    To copy a slice you can use append like this:

    scopy := append([]int{}, s...)
    

    https://play.golang.org/p/lggy5JFL0Z

    package main
    
    import (
        "fmt"
    )
    
    func main() {
    
        out := comb(5, 3)
        fmt.Println(out)
    }
    
    func comb(n, m int) (out [][]int) {
    
        s := make([]int, m)
        last := m - 1
    
        var rc func(int, int)
        rc = func(i, next int) {
    
            for j := next; j < n; j++ {
                s[i] = j
                if i == last {
                    out = append(out, append([]int{}, s...))
                } else {
                    rc(i+1, j+1)
                }
            }
            return
        }
        rc(0, 0)
    
        return out
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题