gpt4 book ai didi

Golang slice 在未修改时更改

转载 作者:IT王子 更新时间:2023-10-29 02:21:31 25 4
gpt4 key购买 nike

我是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 发生了变化。非常感谢!

最佳答案

排队

can = append(can,nums[pos])

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

关于Golang slice 在未修改时更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47218201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com