当我使用golang的append函数创建2D切片时,切片中的先前值发生变化

这是我的代码:


package src


func Subsets(nums []int) [][]int {

    var sets = make([][]int, 0)

    var t = make([]int, 0)

    sets = append(sets, t)

    for i := 0; i < len(nums); i++ {

        for _, v := range sets {

            t = append(v, nums[i])

            sets = append(sets, t)      }

    }

    return sets

}

测试数据是[]int{1,2,3,4,5}

我调试它。发现:


计算sets[22]时,sets[15]由[]int{1,2,3,4}变为[]int{1,2,3,5}


发生了什么。


慕哥6287543
浏览 142回答 1
1回答

哔哔one

问题在于,sets类型的元素引用同一个切片。您最好为 的每个元素创建一个新切片sets。追加不会创建新切片。这是一个修复程序,它复制先前的向量sets而不是简单地扩展它。package srcfunc Subsets(nums []int) [][]int {&nbsp; &nbsp; var sets = make([][]int, 0)&nbsp; &nbsp; var t = make([]int, 0)&nbsp; &nbsp; sets = append(sets, t)&nbsp; &nbsp; for i := 0; i < len(nums); i++ {&nbsp; &nbsp; &nbsp; &nbsp; for _, v := range sets {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t = append([]int(nil), v...) // t is copy of v&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t = append(t, nums[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sets = append(sets, t)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return sets}在这里测试: https:&nbsp;//play.golang.org/p/OZ9nN_t3w9D
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go