Golang 数字排列,递归不起作用

Golang permutations of numbers, recursion not working

代码如下:

package main

import "fmt"

func anon(n []int, sl []int, result [][]int) {
    if len(n) == 0 {
        result = append(result, sl)
        fmt.Printf("result %v\n", result)
        return
    }
    for i , _ := range n {
        fmt.Printf(" n %v\n", n)
        sl = append(sl, n[i])
        ab := append(n[:i], n[i+1:]...)
        fmt.Printf("i %v ---ab %v, sl %v, result %v ---\n",i, ab,sl,result )

        anon(ab, sl , result)
    }
}

func permute(nums []int) [][]int {
    var sl1 = []int{}
    var result = [][]int{}
    anon(nums, sl1, result)
 return result
}

func main() {
  sl2 := []int{1,2}
  permute(sl2)
  
}

我期望 'result' 为 [[1,2], [2,1]]。但是,当我查看代码 运行:

的以下输出时
 n [1 2]
i 0 ---ab [2], sl [1], result [] ---
 n [2]
i 0 ---ab [], sl [1 2], result [] ---
result [[1 2]]

n [2 2]

i 1 ---ab [2], sl [1 2], 结果[] ---

 n [2]
i 0 ---ab [], sl [1 2 2], result [] ---
result [[1 2 2]]

我看到(粗体)i=1,我有 ab[2]、sl[1 2]、result[] 和 n[2,2]。我无法让它为 Golang 工作。类似的东西在 Python.

中效果很好

感谢您的回答。

查看这个完整示例,它可以帮助您更好地理解如何使用 golang 进行排列:https://go.dev/play/p/JKG_FtilQCz

在 Golang 中,切片是指向数组的指针,当您创建 append(n[:i], n[i+1:]...) 时,您是在变量 n 中添加一个新值,因此您正在更改初始 sl2 值,即应该是 {1,2} 但如您所指出的那样转换为 {2,2} 。尽量不要追加 n,而是追加 ab 或其他内容。