我在go操场上有一个示例递归代码,有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)
}
}
去游乐场:https://play.golang.org/p/4e5NIOS9fG4
输出:
[49 63 48 63 49 48 49]
1000101
1001101
1101101
答案 0 :(得分:2)
您需要在递归回溯过程中撤消对主字节片的写操作:
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
}