我试图解决 Go 中的 Leetcode 问题。问题是子集。
这是我用一些调试日志编写的整个代码:
package main
import (
"fmt"
)
func main() {
v := []int{9, 0, 3, 5, 7}
fmt.Println(subsets(v))
}
func subsets(nums []int) [][]int {
result := [][]int{
[]int{}, // empty
}
for _, num := range nums {
fmt.Println("==========")
fmt.Println(num)
fmt.Printf("result = %v\n", result)
temp := [][]int{}
for _, r := range result {
fmt.Printf("r = %v\n", r)
temp = append(temp, append(r, num))
}
for _, t := range temp {
result = append(result, t)
}
fmt.Println("==========")
}
return result
}
(我还准备了Go play ground URL)
这是上面代码的输出:
==========
9
result = [[]]
r = []
==========
==========
0
result = [[] [9]]
r = []
r = [9]
==========
==========
3
result = [[] [9] [0] [9 0]]
r = []
r = [9]
r = [0]
r = [9 0]
==========
==========
5
result = [[] [9] [0] [9 0] [3] [9 3] [0 3] [9 0 3]]
r = []
r = [9]
r = [0]
r = [9 0]
r = [3]
r = [9 3]
r = [0 3]
r = [9 0 3]
==========
==========
7
result = [[] [9] [0] [9 0] [3] [9 3] [0 3] [9 0 3] [5] [9 5] [0 5] [9 0 5] [3 5] [9 3 5] [0 3 5] [9 0 3 5]] // (a)
r = []
r = [9]
r = [0]
r = [9 0]
r = [3]
r = [9 3]
r = [0 3]
r = [9 0 3]
r = [5]
r = [9 5]
r = [0 5]
r = [9 0 5]
r = [3 5]
r = [9 3 5]
r = [0 3 5]
r = [9 0 3 7] // (b)
==========
[[] [9] [0] [9 0] [3] [9 3] [0 3] [9 0 3] [5] [9 5] [0 5] [9 0 5] [3 5] [9 3 5] [0 3 5] [9 0 3 7] [7] [9 7] [0 7] [9 0 7] [3 7] [9 3 7] [0 3 7] [9 0 3 7] [5 7] [9 5 7] [0 5 7] [9 0 5 7] [3 5 7] [9 3 5 7] [0 3 5 7] [9 0 3 7 7]]
让我们看看第5个result。(我在那里指出(a))截至那里,最后一个元素result是[9, 0, 3, 5],这是预期的行为。但是,在那之后,当我尝试在 中写入元素的调试日志时result,它会更改为[9, 0, 3, 7]( (b))。
你知道为什么吗?
qq_花开花谢_0
相关分类