golang 求助大佬

2020-11-07 21:54:16 +08:00
 an93

import "fmt"

func main() {
    input := []int{2,3, 5}
    target := 8
    fmt.Println(combinationSum(input, target))

}

func combinationSum(candidates []int, target int) [][]int {
   var res [][]int

   var backtrack func(int, int, []int)
   backtrack = func(idx int, sum int, nums []int) {

       if sum == target {
           res = append(res, nums)
       }
       if sum >= target {
           return
       }
       for i := idx; i < len(candidates); i++ {
           backtrack(i, sum + candidates[i], append(nums,candidates[i]))
       }
   }
   backtrack(0, 0, []int{})
   return res
}

这段代码结果有问题, 而且问题处在 res = append(res, nums) 这一行, 如果我把 nums copy 一个再 append 就不会有问题了,听说这里大神比较多,求大神们指教一下

959 次点击
所在节点    问与答
3 条回复
an93
2020-11-07 21:57:07 +08:00
luguhu
2020-11-07 22:28:41 +08:00
slice 是指针传递
zhouenxian
2020-11-08 07:39:49 +08:00
函数传参数确实是值传递,但 slice 传递的值中包含了内容的地址,所以还是把地址传了进去。
如下为切片类型的内部定义。
type _slice struct {
elements unsafe.Pointer // 引用着底层存储在间接部分上的元素
len int // 长度
cap int // 容量
}
引用:go 101,https://gfw.go101.org/article/container.html

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/722783

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX