1 回答
TA贡献1835条经验 获得超7个赞
append需要时更改r:而
不是:
temp = append(temp, append(r, num))
您可以使用:
rr := make([]int, len(r))
copy(rr, r)
rr = append(rr, num)
temp = append(temp, rr)
你很高兴:
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)
// append(r, num)
rr := make([]int, len(r))
copy(rr, r)
rr = append(rr, num)
temp = append(temp, rr)
}
for _, t := range temp {
result = append(result, t)
}
fmt.Println("==========")
}
return result
}
只需调试您的代码,您就会看到,它发生在这里:
temp := [][]int{}
for _, r := range result {
fmt.Println("result =", result, len(result), cap(result))
fmt.Println("r ==", r, len(r), cap(r))
fmt.Println("num =", num)
rr := append(r, num)
fmt.Println("r ==", r, len(r), cap(r))
fmt.Println("rr ==", rr, len(rr), cap(rr))
fmt.Println("result =", result, len(result), cap(result))
fmt.Println("temp =", temp)
temp = append(temp, rr)
fmt.Println("temp =", temp)
}
什么时候
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]] 16 16
r == [9 0 3] 3 4
num = 7
r == [9 0 3] 3 4
rr == [9 0 3 7] 4 4
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 7]] 16 16
因为:
append(r, num)
- 1 回答
- 0 关注
- 101 浏览
添加回答
举报