dongyuan9892 2019-04-04 22:59
浏览 42

递归期间缺少排列

I have go a sample recursive code in go playground, there are 2 "?", the target is to generate all binary strings replacing ? with 0 or 1 , it supposes to display 4 results, but only display 3. ie missing 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)
    }

}

Go playground: https://play.golang.org/p/4e5NIOS9fG4

Output:

[49 63 48 63 49 48 49]
1000101
1001101
1101101
  • 写回答

1条回答 默认 最新

  • drv16821 2019-04-04 23:48
    关注

    You need to undo the writes to the master byte-slice during recursive-backtracking:

    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

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?