I'm attempting to solve the Subsets problem on LeetCode using Go. I've come up with the following solution:
func subsets(nums []int) [][]int {
sol := make([][]int,0)
temp:= make([]int,0)
var backtrack func(idx int)
backtrack = func(idx int) {
sol = append(sol, temp)
fmt.Println(temp, append([]int{},temp...))
if idx == len(nums) {
return
}
for i:= idx; i<len(nums);i++{
temp = append(temp,nums[i])
backtrack(i+1)
temp = temp[:len(temp)-1]
}
}
backtrack(0)
return sol
}
However, this solution is incorrect. I have noticed that I need to use append(sol, append([]int{}, temp...)) instead of just sol = append(sol, temp).
Even though the fmt.Println(temp, append([]int{}, temp...)) statement produces the same output for both temp and append([]int{}, temp...), the corrected version using append([]int{}, temp...) actually works. Can someone explain the difference between temp and append([]int{}, temp...) in this context? Why does the corrected version work while the initial version does not?
Expected temp
and append([]int{},temp...)
to be the same