Golang切片在未修改时发生了变化



我是go的新手,我尝试使用它来完成一些leetcode问题 https://leetcode.com/problems/subsets-ii/description/。但是我无法得到正确的答案,当我尝试调试它时,当我不对它执行任何操作时,我发现一些变量发生了变化。

package main
import (
    "fmt"
    "sort"
)
func get_set(nums []int, can []int, pos int, last_in bool) [][]int{
    if pos == len(nums) {
        res := [][]int{can}
        fmt.Println("Return:")
        fmt.Println(res)
        return res
    }
    f_res := [][]int{}
    if !last_in || ( pos > 0 && nums[pos]!=nums[pos-1] ){
        first_res := get_set(nums,can,pos+1,false)
        fmt.Println("First")
        fmt.Println(first_res)
        f_res = append(f_res,first_res...)
        fmt.Println("f_res")
        fmt.Println(f_res)
    }
    // Problem is here
    fmt.Println("f_res")
    fmt.Println(f_res)
    fmt.Println(can)
    can = append(can,nums[pos])
    fmt.Println(can)
    // Problem is here
    fmt.Println("f_res")
    fmt.Println(f_res)
    second_res := get_set(nums,can,pos+1,true)
    fmt.Println("Second")
    fmt.Println(second_res)
    f_res = append(f_res,second_res...)
    fmt.Println("Total")
    fmt.Println(f_res)
    return f_res
}
func subsetsWithDup(nums []int) [][]int {
    res := make([][]int,0)
    sort.Ints(nums)
    con := make([]int,0)
    res = get_set(nums,con,0,false)
    return res
}
func main()  {
    nums := []int{1,2,3,4,5}
    res := subsetsWithDup(nums)
    fmt.Println(res)
    //for _,l := range res{
    //  fmt.Println(l)
    //}
}

打印信息为:

...
Total
[[1 2 3] [1 2 3 5]]
First
[[1 2 3] [1 2 3 5]]
f_res
[[1 2 3] [1 2 3 5]]
f_res
[[1 2 3] [1 2 3 5]]
[1 2 3]
[1 2 3 4]
f_res
[[1 2 3] [1 2 3 4]]
...

为什么当我附加一些值到 con 时变量f_res更改。谢谢!

in line

can = append(can,nums[pos])

您正在修改函数参数,这被认为是一种不好的做法。而是创建一个新切片并从can切片中复制值。

相关内容

最新更新