When I append to a slice of type [][]int, the result is not what I expected. I have code below that illustrates the problem and has a fix. But I would like to understand what exactly is going on
The functioning code is at https://play.golang.org/p/aeibeDW17z2 The one that is broken is at https://play.golang.org/p/eP5MiH1VjSu
This is from the leetcode problem https://leetcode.com/problems/combination-sum
Could someone please explain what exactly is going on? I beleive its got to do with reuse of the backing array.. but don't really understand.
Thanks in advance
Problematic Code
if target == 0 {
fmt.Println("Current Result:", currResult)
fmt.Println("Result Before:", result)
r := append([]int{}, currResult...)
fmt.Println("r=", r)
//*result = append(*result, r)
// if you uncomment above line and comment below, you will get right result - Why?
*result = append(*result, currResult)
fmt.Println("Result:", *result)
return
}
Working Code
package main
import (
"fmt"
)
import "sort"
func combinationSum(candidates []int, target int) [][]int {
sort.Ints(candidates)
result := [][]int{}
helper(candidates, target, 0, []int{}, &result)
return result
}
func helper(candidates []int, target int, pos int, currResult []int, result *[][]int){
if pos == len(candidates) || target < 0 {
return
}
if target == 0 {
fmt.Println("Current Result:", currResult)
fmt.Println("Result Before:", result)
r := append([]int{}, currResult...)
fmt.Println("r=", r)
*result = append(*result, r)
// if you comment above line and uncomment below, you will get wrong result - Why?
//*result = append(*result, currResult)
fmt.Println("Result:", *result)
return
}
// lets see if we can optimize this call
for i := pos; i < len(candidates); i++ {
temp := append(currResult, candidates[i])
helper(candidates, target-candidates[i], i, temp, result)
}
}
func main() {
candidates :=[]int{2,3,5}
target := 8
fmt.Println("Input:
-----
","Target:", target, "Candidates:", candidates )
//fmt.Println("Target:", target, "Candidates:", candidates)
fmt.Println("
Debug
-----")
result :=combinationSum(candidates, 8)
fmt.Println("
Results:
------
", result)
}