今天我试着去做我的第一步。 我试着编写一个函数,它创建给定列表的所有排列。 首先我完全失败了,所以我尝试用python编写函数并逐步翻译它:
蟒:
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]))
转到:
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] [3 3 3] [3 3 3] [3 3 3] [3 3 3] [3 3 3]]
我真的有人可以帮助我。我真的很想知道,我在go代码中做错了什么
答案 0 :(得分:2)
getPermutations
函数每次迭代都会改变原始的elements
切片。在修改之前,您需要复制该切片。
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
}