I was recently doing a backtracking question and came across this weird scenario which I am not able to understand. This question is related to listing out all the possible subsets possible from the given array. Here is the code snippet:
func subsets(A []int) [][]int {
sort.Ints(A)
res, cur := [][]int{}, []int{}
if len(A) == 0 {
return append(res, cur)
}
subsetsUtil(A, 0, &res, cur)
return res
}
func subsetsUtil(A []int, n int, res *[][]int, cur []int) {
*res = append(*res, append([]int{}, cur...))
for i := n; i < len(A); i++ {
cur = append(cur, A[i])
subsetsUtil(A, i+1, res, cur)
cur = cur[:len(cur)-1]
}
}
This code snippet gives me the correct answer but if I remove the pointer to the result slice, i.e.
func subsets(A []int) [][]int {
sort.Ints(A)
res, cur := [][]int{}, []int{}
if len(A) == 0 {
return append(res, cur)
}
subsetsUtil(A, 0, res, cur)
return res
}
func subsetsUtil(A []int, n int, res [][]int, cur []int) {
res = append(res, append([]int{}, cur...))
for i := n; i < len(A); i++ {
cur = append(cur, A[i])
subsetsUtil(A, i+1, res, cur)
cur = cur[:len(cur)-1]
}
}
Code doesn't work and returns me an empty slice. As far as I understand, slices are passed by reference and not by value, then how is it when I pass the pointer to the result slice, code works and gives me the correct result but for the other case, it is returning me an empty slice? What am I missing?