亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

切片神奇地更新

切片神奇地更新

Go
小唯快跑啊 2022-06-21 10:39:09
我正在嘗試編寫一個程序來查找二叉樹中的所有從根到葉的路徑,其中每個路徑的總和等于給定的總和。以下是我想出的代碼package mainimport (    "fmt")type TreeNode struct {     Val int     Left *TreeNode     Right *TreeNode}func main() {    root := TreeNode{       Val : 5,       Left: &TreeNode {            Val : 4,           Left : &TreeNode {                Val : 11,                Left : &TreeNode { Val : 2},                Right : &TreeNode { Val : 7},                        },                },    }        paths := [][]int{}    pathSumRecursive(&root, 22, []int{}, &paths)    fmt.Println("paths:", paths)}func pathSumRecursive(root *TreeNode, sum int, currentPath []int, paths *[][]int) {    if root == nil {        return     }        currentPath = append(currentPath, root.Val)        if root.Left == nil && root.Right == nil && root.Val == sum {        *paths = append(*paths, currentPath)        fmt.Println("paths updated ", *paths)        return    }         pathSumRecursive(root.Left, sum-root.Val, currentPath, paths)     pathSumRecursive(root.Right, sum-root.Val, currentPath, paths)    }該程序的輸出是paths updated  [[5 4 11 2]]paths: [[5 4 11 7]]我不明白的是附加的值,paths它只[5 4 11 2]更新了一次。那么是什么導致2(最后一個元素)更新為7?我知道切片是按值傳遞的,切片值是標題,描述了支持數組的連續部分。但是我仍然不明白該值是如何在隨后的遞歸中被替換的。
查看完整描述

1 回答

?
偶然的你

TA貢獻1841條經驗 獲得超3個贊

Go 中的切片是包含指向底層數組的指針、長度和容量的小描述符。有關更多詳細信息,請參閱切片內部。

將切片傳遞給函數時,會復制描述符,但不會復制底層數組。這意味著currentPath它將始終指向相同的底層數組,但通過遞歸將具有不同的值:

  • 在節點11currentPath = [5 4 11]

  • 在節點2currentPath =  [5 4 11 2]。添加到paths長度 4。

  • 備份到節點11currentPath = [5 4 11]

  • 在節點7currentPath = [5 4 2 7]。

在 node7中,底層數組仍然是相同的,并且與存儲在paths. 但是節點 7 現在附加7到長度為 3 的切片上,覆蓋了2底層數組中的先前值。

一個快速的解決方案是復制currentPathinto的內容,path而不是直接存儲切片:

   if root.Left == nil && root.Right == nil && root.Val == sum {

        newSlice := make([]int, len(currentPath))

        copy(newSlice, currentPath)

        *paths = append(*paths, newSlice)

        fmt.Println("paths updated ", *paths)

        return

    }

重要說明:當切片需要增長時,會復制底層數組,從而產生一個單獨的數組。在示例中,切片在節點處增長到 4 的容量,因此它在節點和4處保持相同的底層數組。如果它在 node 增長,添加到的切片不會與任何人共享其底層數組。272path


查看完整回答
反對 回復 2022-06-21
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號