0

I was defining a function that returns all the subsets (power set) of a list of integers. Example: [1,2,3] -> [[], [1], [2], [3], [1,2], [2,3], [1,3], [1,2,3]]

The code I wrote is as follows :-

func subsets(nums []int) [][]int {
    out := make([][]int, 0)
    out = append(out, []int{})
    for _, num := range nums {
        n := len(out)
        for i:=0; i<n; i++ {
            out = append(out, append(out[i], num))
        }
    }
    return out
}

Which adds the next number in the list to all the previous subsets.

Output when input = [9,0,3,5,7]

Upto input length <= 4, the function runs fine. But when it is more than that, some weird behaviour occurs, like the out should be appended [9,0,3,5] but it appends [9,0,3,7] (input list [9,0,3,5,7])

What could be the reason behind this peculiar behaviour?

JimB
  • 104,193
  • 13
  • 262
  • 255
  • You are assigning the inner `append` to a different value from its first argument, which may or may not still refer to the same backing array. See the [slice spec](https://go.dev/ref/spec#Slice_types), [Tour of Go: Slices](https://go.dev/tour/moretypes/7) or the [blog post on slices](https://go.dev/blog/slices) for more detailed information. – JimB Feb 09 '23 at 13:57

0 Answers0