go - 递归期间缺少排列

标签 go recursion

我在 go playground 中有一个示例递归代码,有 2 个“?”,目标是生成所有二进制字符串替换 ?使用 0 或 1,它应该显示 4 个结果,但只显示 3 个。即缺少 1100101

package main

import (
    "fmt"
    //"strings"
    //"strconv"
)

func main() {
    str := "1?0?101"
    mstr := []byte(str)
    q := []byte("?")[0]
    a := []byte("0")[0]
    b := []byte("1")[0]
    fmt.Println(mstr)
    allstr(mstr, 0, len(mstr), q, a, b)

}

func allstr(mstr []byte, index int, size int, q, a, b byte) {

    if index >= size {
        fmt.Println(string(mstr))
        return
    }
    if mstr[index] == q {
        mstr[index] = a
        allstr(mstr, index+1, size, q, a, b)

        mstr[index] = b
        allstr(mstr, index+1, size, q, a, b)

    } else {

        allstr(mstr, index+1, size, q, a, b)
    }

}

去 Playground :https://play.golang.org/p/4e5NIOS9fG4

输出:

[49 63 48 63 49 48 49]
1000101
1001101
1101101

最佳答案

您需要在递归回溯期间撤消对主 byte slice 的写入:

if mstr[index] == q {
        mstr[index] = a
        allstr(mstr, index+1, size, q, a, b)

        mstr[index] = b
        allstr(mstr, index+1, size, q, a, b)

        mstr[index] = q         // <--- add this
} 

https://play.golang.org/p/-JEsVGFcsQo

关于go - 递归期间缺少排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55526076/

相关文章:

recursion - 谁能解释一下 prolog 使用这个递归程序执行的步骤吗?

递归和大 O

go - 收到 "bytes.Buffer does not implement io.Writer"错误消息

arrays - 无效操作 : index of type *int golang

go - 从 Go 程序中获取保留字列表

Python Quicksort 函数进入无限循环

json - 多个Json条目到一个结构

go - 使用golang的mgo库,如何获取列表等嵌套对象

algorithm - 将线性递归函数重写为尾递归函数

linux - 在 Linux CLI 中以相对于当前目录的路径递归列出文件