今天我试着用go做我的第一步。我试图编写一个函数,它创建给定列表的所有排列。首先,我完全失败了,所以我尝试用python编写函数,并逐步将它翻译成这样:
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
我真的有人能帮我。我真的很想知道,我在go代码中做错了什么
发布于 2017-02-03 16:18:15
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
}https://stackoverflow.com/questions/42028130
复制相似问题