一个全排列的问题,用递归回溯给切片赋值,最后输出的是最后一次递归的数组。怎么解决这个问题,困扰了一上午。
package main
import (
"fmt"
)
func swap(nums []int, i, j int) {
temp := nums[i]
nums[i] = nums[j]
nums[j] = temp
}
func permute(nums []int) [][]int {
length := len(nums) - 1
var res [][]int
dfs1(nums, 0, length, &res)
fmt.Println(res)
return res
}
func dfs1(nums []int, cur, end int, res *[][]int) {
if cur == end {
*res = append(*res, nums)
return
} else {
for i := cur; i <= end; i++ {
swap(nums, cur, i)
dfs1(nums, cur+1, end, res)
swap(nums, cur, i)
}
}
}
func main() {
nums := []int{4, 5, 6}
permute(nums)
}
输出的
[[4 5 6] [4 5 6] [4 5 6] [4 5 6] [4 5 6] [4 5 6]]