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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器