
(编码问题是生成所有组合的解决方案,这些组合的总和达到目标,候选arr中每个元素的次数不受限制。)
二维 [][]int 切片 theList 在附加 []int (tmpCombo) 的递归中通过引用传递,但附加后,其中一个元素被修改,[3 3 3 3 3 3] 更改为 [3 3 3 3 3 2]。所以我必须在执行 append() 之前复制 tmpCombo 。 append(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 重新分配/更新新的长度,并且同一位置的基础数据被修改(未重新分配时)。
make()新建切片并copy()结束(make()分配具体容量)
或
append(nil []int, arr...]. (append() 可能会分配更多内存,但适合频繁修改)
以上就是append() 可能会修改原始切片(2d 切片递归)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号