首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Go语言创建排列

Go语言创建排列
EN

Stack Overflow用户
提问于 2017-02-03 15:54:12
回答 1查看 638关注 0票数 0

今天我试着用go做我的第一步。我试图编写一个函数,它创建给定列表的所有排列。首先,我完全失败了,所以我尝试用python编写函数,并逐步将它翻译成这样:

python:

代码语言:javascript
运行
复制
def get_permutations(elements):
    permutations = []
    if len(elements) == 1:
        return [elements]
    for i in range(len(elements)):
        for perm in get_permutations(elements[0:i] +  elements[i+1:]):
            permutations.append([elements[i]] + perm)
    return permutations

print(get_permutations([1,2,3]))

去:

代码语言:javascript
运行
复制
func getPermutations(elements []int) [][]int {
    permutations := [][]int{}
    if len(elements) == 1 {
        permutations = [][]int{elements}
        return permutations
    }
    for i := range elements {
        for _, perm := range getPermutations(append(elements[0:i], elements[i+1:]...)) {
            permutations = append(permutations, append([]int{elements[i]}, perm...))
        }
    }
    return permutations
}

func main() {
    x := getPermutations([]int{1, 2, 3})
    fmt.Print(x)
}

虽然python版本创建了这个输出:

[1,2,3,1,3,2,2,1,3,2,3,1,3,1,2,3,2,1]

go版本创建了这个版本:

[3 3 3

我真的有人能帮我。我真的很想知道,我在go代码中做错了什么

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-03 16:18:15

getPermutations函数在每次迭代时都会对原始的elements切片进行变异。在修改该切片之前,您需要对其进行复制。

代码语言:javascript
运行
复制
func getPermutations(elements []int) [][]int {
    permutations := [][]int{}
    if len(elements) == 1 {
        permutations = [][]int{elements}
        return permutations
    }
    for i := range elements {
        el := make([]int, len(elements))
        copy(el, elements)

        // or copy via append
        // el := append([]int(nil), elements...)

        for _, perm := range getPermutations(append(el[0:i], el[i+1:]...)) {
            permutations = append(permutations, append([]int{elements[i]}, perm...))
        }
    }
    return permutations
}

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42028130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档