第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

golang給一個(gè)int數(shù)組追加一個(gè)數(shù)字,數(shù)組中相鄰元素的值發(fā)生變化,為什么?

golang給一個(gè)int數(shù)組追加一個(gè)數(shù)字,數(shù)組中相鄰元素的值發(fā)生變化,為什么?

Go
MMMHUHU 2022-10-24 09:21:41
我正在嘗試使用 Golang 解決一些動(dòng)態(tài)編程問(wèn)題。我寫了一個(gè)函數(shù)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]}部分結(jié)果如下。...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]當(dāng)程序?qū)?retAry[5] 從 [5] 替換為 [1 1 1 2] 時(shí),retAry[4] 中的數(shù)組從 [1 1 1 1] 更改為 [1 1 1 2]。發(fā)生什么事?但是,如果替換  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]誰(shuí)能幫助解釋我犯了什么錯(cuò)誤?代碼在這里
查看完整描述

1 回答

?
海綿寶寶撒

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊

However, if replace  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] 之間共享相同的數(shù)組。如果您修改一個(gè)切片,則其他切片也可以更改。


func main() {

    s1 := append([]int{}, 1, 2, 3) // len: 3, cap 4 []int{1, 2, 3, 0}


    // it appends 4 to 4th index and assign new slice to s2.

    // s2 is share the same array with s1

    // s1 : len: 3, cap 4 []int{1, 2, 3, 4}

    // s2 : len: 4, cap 4 []int{1, 2, 3, 4}

    s2 := append(s1, 4)


    // s3 is share the same array with s1 and s2 as well

    // when you append 4th index to s1, and assign to s3, both s1 and s2 will change as well

    // s1 : len: 3, cap 4 []int{1, 2, 3, 5}

    // s2 : len: 4, cap 4 []int{1, 2, 3, 5}

    // s3 : len: 4, cap 4 []int{1, 2, 3, 5}

    s3:= append(s1, 5)

    fmt.Println(s2, s3) // output [1 2 3 5] [1 2 3 5]

}

retAry[i+num] = append([]int{num}, retAry[i]...) 


[]int{num}您使用新數(shù)組初始化新切片,然后將 retAry[i] 中的每個(gè)元素附加到新數(shù)組。它們不再是 retAry[i+num] 和 retAry[i] 之間的任何引用。


查看完整回答
反對(duì) 回復(fù) 2022-10-24
  • 1 回答
  • 0 關(guān)注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)