I'm trying to implement a golang function to solve the array subset problem. I'm having an issue hard copying a slice of ints to my 2D slice:
// Subsets
func Subsets(nums []int) [][]int {
// create 2D slice
sets := make([][]int, 0)
backtrack(sets, make([]int, 0), nums, 0)
return sets
}
func backtrack(sets [][]int, tempList []int, nums []int, start int) {
// insert current list
sets = append(sets, tempList) // <---------HERE
for i := start; i < len(nums); i++ {
tempList = append(tempList, nums[i])
backtrack(sets, tempList, nums, i+1)
tempList = tempList[:len(tempList)-1]
}
}
I tried replace the append statement with:
buffer := make([]int, len(tempList))
copy(buffer, tempList)
sets = append(sets, buffer)
however I still see the sets slices empty when the program ends. An identical copy of this function works just fine in java with the append line as follow:
list.add(new ArrayList<>(tempList));
what's the correct way to do this in golang?