首頁  >  文章  >  後端開發  >  append() 可能會修改原始切片(2d 切片遞迴)

append() 可能會修改原始切片(2d 切片遞迴)

WBOY
WBOY轉載
2024-02-06 08:27:04400瀏覽

append() 可能会修改原始切片(2d 切片递归)

问题内容

(编码问题是生成所有组合的解决方案,这些组合的总和达到目标,候选arr中每个元素的次数不受限制。)

二维 [][]int 切片 theList 在附加 []int (tmpCombo) 的递归中通过引用传递,但附加后,其中一个元素被修改,[3 3 3 3 3 3] 更改为 [3 3 3 3 3 2]。所以我必须在执行 append() 之前复制 tmpComboappend(arr, ele) 是否更改了原始 arr 切片?如果是这样,我应该观察到更多原始的 arr 被修改,但这种情况只发生一次。所以我实际上很困惑这个切片 append() 是如何工作的。

https://go.dev/play/p/PH10SxiF7A5

<code>
...
theList: [.... [3 3 3 3 3 3]]
theList: [.... [3 3 3 3 3 2] [3 3 3 3 2 2 2]]
</code>

(我还尝试执行 for 循环并继续附加到切片,原始切片根本没有改变...)

package main

import (
    "fmt"
    "sort"
)

func combinationSum(candidates []int, target int) [][]int {
    sort.Sort(sort.Reverse(sort.IntSlice(candidates)))

    var theList [][]int
    var tmpCombo []int
    rCombo(candidates, target, 0, tmpCombo, &theList)

    return theList
}

func rCombo(candidates []int, target int, index int, tmpCombo []int, theList *[][]int) {
    if index >= len(candidates) {
        fmt.Println("index:", index)
        return
    }
    // fmt.Println(target)
    if candidates[index] > target {
        rCombo(candidates, target, index+1, tmpCombo, theList)
        return
    }

    for i:=index; i<len(candidates); i++ {
        if candidates[i] < target {
                rCombo(candidates, target-candidates[i], i, append(tmpCombo, candidates[i]), theList)
        } else if candidates[i] == target {

            // NOTE: simply append tmpCombo will give weird output [3 3 3 3 3 3] changed to [3 3 3 3 3 2].              
            *theList = append(*theList,  append(tmpCombo, target))

            // cpyCombo := make([]int, len(tmpCombo))
            // copy(cpyCombo, tmpCombo)
            // *theList = append(*theList,  append(cpyCombo, target))

            // appended slice didn't change address so tmpCombo was modified
            for i:=0; i<len(*theList); i++ {
                fmt.Printf("%d %p ", (*theList)[i], (*theList)[i])
            }
            fmt.Println()

            // fmt.Println("cc", tmpCombo, candidates[i], append(cpyCombo, candidates[i]), theList )
        }
    }
}

func main() {
    // 2,3,5
    candidates := []int{7,3,2}
    target := 18
    combinationSum(candidates, target)

 // test: this does not change the original s...
// var s []int = make([]int, 6)
// // var x []int

// for i:=0; i<200; i++ {
//  x := append(s, i)
//  fmt.Println(x, s)
// }
}

正确答案


由于这个答案说明了同一问题,我现在明白了https://www.php.cn/link/0d924f0e6b3fd0d91074c22727a53966一个>.

基本上,如果切片将数据存储在具有指定容量的一个位置,但将长度作为单独的属性...在我的情况下,执行多个 append(tmpCombo, target) 实际上会修改 tmpCombo 中的数据,因为该变量是' t 重新分配/更新新的长度,并且同一位置的基础数据被修改(未重新分配时)。

tldr。确保使用以下任一方式传递相同数据的新副本:

make()新建切片并copy()结束(make()分配具体容量)

append(nil []int, arr...]. (append() 可能会分配更多内存,但适合频繁修改)

以上是append() 可能會修改原始切片(2d 切片遞迴)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除