golang给一个int数组追加一个数字,数组中相邻元素的值发生变化,为什么?

我正在尝试使用 Golang 解决一些动态编程问题。我写了一个函数


func main() {

    fmt.Println(HowSum(5, []int{1, 2, 5}))

}


func HowSum(targetNum int, numbers []int) []int {

  retAry = make([][]int, targetNum+1)

  retAry[0] = make([]int, 0)

  for i := 0; i <= targetNum; i++ {

    if retAry[i] != nil {

      for _, num := range numbers {

        if i+num <= targetNum {

          fmt.Print("Before:", i, " round, num =", num, retAry, "\n")

          retAry[i+num] = append(retAry[i], num)

          fmt.Print("After :", i, " round, num =", num, retAry, "\n\n")

        }

      }

    }

  }

  return retAry[targetNum]

}

部分结果如下。


...

Before:3 round, num =2 [[] [1] [1 1] [1 1 1] [1 1 1 1] [5]]

After :3 round, num =2 [[] [1] [1 1] [1 1 1] [1 1 1 2] [1 1 1 2]]

...

[1 1 1 2 1]

当程序将 retAry[5] 从 [5] 替换为 [1 1 1 2] 时,retAry[4] 中的数组从 [1 1 1 1] 更改为 [1 1 1 2]。发生什么事?


但是,如果替换  retAry[i+num] = append(retAry[i], num)为retAry[i+num] = append([]int{num}, retAry[i]...),我可以得到正确的答案。


...

Before:3 round, num =2 [[] [1] [1 1] [1 1 1] [1 1 1 1] [5]]

After :3 round, num =2 [[] [1] [1 1] [1 1 1] [1 1 1 1] [2 1 1 1]]

...

[1 1 1 1 1]


谁能帮助解释我犯了什么错误?

代码在这里


MMMHUHU
浏览 143回答 1
1回答

海绵宝宝撒

However, if replace&nbsp; retAry[i+num] = append(retAry[i], num) to retAry[i+num] = append([]int{num}, retAry[i]...) , I can get the correct answer.解释:retAry[i+num] = append(retAry[i], num)在 retAry[i+num] 和 retAry[i] 之间共享相同的数组。如果您修改一个切片,则其他切片也可以更改。func main() {&nbsp; &nbsp; s1 := append([]int{}, 1, 2, 3) // len: 3, cap 4 []int{1, 2, 3, 0}&nbsp; &nbsp; // it appends 4 to 4th index and assign new slice to s2.&nbsp; &nbsp; // s2 is share the same array with s1&nbsp; &nbsp; // s1 : len: 3, cap 4 []int{1, 2, 3, 4}&nbsp; &nbsp; // s2 : len: 4, cap 4 []int{1, 2, 3, 4}&nbsp; &nbsp; s2 := append(s1, 4)&nbsp; &nbsp; // s3 is share the same array with s1 and s2 as well&nbsp; &nbsp; // when you append 4th index to s1, and assign to s3, both s1 and s2 will change as well&nbsp; &nbsp; // s1 : len: 3, cap 4 []int{1, 2, 3, 5}&nbsp; &nbsp; // s2 : len: 4, cap 4 []int{1, 2, 3, 5}&nbsp; &nbsp; // s3 : len: 4, cap 4 []int{1, 2, 3, 5}&nbsp; &nbsp; s3:= append(s1, 5)&nbsp; &nbsp; fmt.Println(s2, s3) // output [1 2 3 5] [1 2 3 5]}retAry[i+num] = append([]int{num}, retAry[i]...)&nbsp;[]int{num}您使用新数组初始化新切片,然后将 retAry[i] 中的每个元素附加到新数组。它们不再是 retAry[i+num] 和 retAry[i] 之间的任何引用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go