我正在使用递归解决 leetcode 中的问题。但是,用作参数的值在方法中发生了变化。
package main
import "fmt"
func makeCmbs(cmbs [][]int, nums []int, remains []int, k int) [][]int {
fmt.Println("==", cmbs, nums, remains, k) // (2)
if k == 0 {
cmbs = append(cmbs, nums)
fmt.Println("!", nums, cmbs)
return cmbs
}
for i, num := range remains {
fmt.Printf("-[%d] num:%d cmbs:%v remains:%v\n", i, num, cmbs, remains) // (1) cmbs here is [[1,2,3,4]]
cmbs = makeCmbs(cmbs, append(nums, num), remains[i+1:], k-1) // cmbs in makeCmbs method is [[1,2,3,5]] ???
fmt.Printf("+[%d] num:%d cmbs:%v\n", i, num, cmbs)
}
return cmbs
}
func combine(n int, k int) [][]int {
remains := make([]int, n)
for i := 0; i < n; i++ {
remains[i] = i + 1
}
return makeCmbs([][]int{}, []int{}, remains, k)
}
func main() {
combine(5, 4)
}
Bellow是它输出的开始。
== [] [] [1 2 3 4 5] 4
-[0] num:1 cmbs:[] remains:[1 2 3 4 5]
== [] [1] [2 3 4 5] 3
-[0] num:2 cmbs:[] remains:[2 3 4 5]
== [] [1 2] [3 4 5] 2
-[0] num:3 cmbs:[] remains:[3 4 5]
== [] [1 2 3] [4 5] 1
-[0] num:4 cmbs:[] remains:[4 5]
== [] [1 2 3 4] [5] 0
! [1 2 3 4] [[1 2 3 4]]
+[0] num:4 cmbs:[[1 2 3 4]]
-[1] num:5 cmbs:[[1 2 3 4]] remains:[4 5] <---- cmbs is [[1 2 3 4]]
== [[1 2 3 5]] [1 2 3 5] [] 0 <---- why [[1 2 3 5]] ???
正如你所看到的最后两行,cmbs [[1 2 3 4]] 变成了 [[1 2 3 5]]。谁能给我一个线索,为什么在 makeCmbs 方法中改变 cmbs 值?
MYYA
相关分类