algorithm - 附加字符串和数组的类似 Go 函数未按预期运行

标签 algorithm go

我有两个 Go 函数:

func permutation(prefix, str []int) {
    n := len(str)
    if n == 0 {
        fmt.Println(prefix)
    } else {
        for i := 0; i < n; i++ {
            permutation(
                append(prefix, str[i]),
                append(str[0:i], str[i+1:]...),
            )
        }
    }
}

func perms(prefix, str string) {
    n := len(str)
    if n == 0 {
        fmt.Println(prefix)
    } else {
        for i := 0; i < n; i++ {
            perms(
                prefix+string(str[i]),
                string(str[0:i])+string(str[i+1:]),
            )
        }
    }
}

第一个接受一个整数数组,第二个接受一个字符串。然后他们都计算数组或字符串的所有排列。

我可以这样运行它们:

permutation([]int{}, []int{1, 2, 3})
perms("", "123")

它们的输出不一样:

$ go run main.go
[1 2 3]
[1 3 3]
[3 3 3]
[3 3 3]
[3 3 3]
[3 3 3]
123
132
213
231
312
321

我想追加我遗漏的数组有一些细微差别。我似乎无法弄清楚。知道发生了什么事吗?

最佳答案

虽然 str1+str2 确实返回新的(在内存方面不相关)字符串,但 append 不会以这种方式运行。例如append(str[0:i], str[i+1:]...)会破坏str的原始内容,覆盖str[i :]str[i+1:]。这是因为 str[0:i] 可以在不分配新缓冲区的情况下追加 str[i+1:]

解决方案是在每次迭代中创建一个全新的数组。至少对于 str,因为 append(prefix, str[i]) 不受此问题的影响。例如:

for i := 0; i < n; i++ {
    var s []int
    s = append(s, str[0:i]...)
    s = append(s, str[i+1:]...)
    permutation(append(prefix, str[i]), s)
}

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

关于 slice 和追加机制的更多信息:

http://blog.golang.org/go-slices-usage-and-internals

https://blog.golang.org/slices

关于algorithm - 附加字符串和数组的类似 Go 函数未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33848258/

相关文章:

algorithm - 改进 next_permutation 算法

go - 在选择中的同一 channel 上读写

go - 如何在 Go 中实现 PHP 函数 `die()`(或 `exit()`)?

image-processing - 如何让 golang 读取 jpeg 并获得与 Python/C 相同的 unit8 值?

go - 如何为 Go 中的行插入重用单个 Postgres DB 连接?

algorithm - 遍历具有负节点和循环节点的图的最佳算法是什么

GIT,工作目录是如何填充的

algorithm - 如何计算a列中每对值之间b列中共享值的数量?

python - 搜索函数python

excel - 在 Go 中计算反对数范数