I am trying to solve the subsetting problem on LeetCode using Go. I came 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 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 generates the same output for temp and append([]int{}, temp...), use append([ The corrected version of ]int{}, temp...) actually works. Can someone explain the difference between temp and append([]int{}, temp...) in this case? Why does the corrected version work but the initial version doesn't?
Expectedtemp
is the same as append([]int{},temp...)
sol =append(sol, temp)
The problem is that you are adding the slice temp
to the sol
instead of the item "inside" the slice. As stated in the Slice internal blog post, a slice is "just" a pointer to an array, its length and capacity.
So, in your case, since temp
is reused in each iteration, the array contents under the temp
slice will be overwritten, and The values inside the slice you previously added to sol
will also be overwritten as modified (because the array under the slice has been modified). This is why you end up with wrong results, even though your fmt.Println
statement appears before appending temp
with the correct value.
When append([]int{}, temp...)
creates a new slice, the value within the new slice cannot change because it is not reused.
The above is the detailed content of Strange behavior of append in Go. For more information, please follow other related articles on the PHP Chinese website!