append
заменяет r
при необходимости: Вместо:
temp = append(temp, append(r, num))
Вы можете использовать:
rr := make([]int, len(r))
copy(rr, r)
rr = append(rr, num)
temp = append(temp, rr)
, и вы можете go:
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)