附加到[] [] int切片时结果错误-CombinationSum问题

时间:2019-09-11 21:36:54

标签: go

当我附加到[] [] int类型的切片时,结果不是我期望的。我下面有说明问题的代码并已解决。但是我想了解到底发生了什么

有效代码位于https://play.golang.org/p/aeibeDW17z2 损坏的是https://play.golang.org/p/eP5MiH1VjSu

这是来自leetcode问题 https://leetcode.com/problems/combination-sum

有人可以解释到底发生了什么吗?我相信它与支持数组的重用有关。但是我不太了解。

预先感谢

问题代码

    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
    }

工作代码

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:\n-----\n","Target:", target, "Candidates:", candidates )
    //fmt.Println("Target:", target, "Candidates:", candidates)

    fmt.Println("\nDebug\n-----")
    result :=combinationSum(candidates, 8)

    fmt.Println("\n\nResults:\n------\n", result)


}

0 个答案:

没有答案