golang slice 值与地址的问题

46.Permutations

Medium

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

leetcode用golang去做,发现一个问题

func permute(nums []int) [][]int {
    res := [][]int{}
    helper(nums,[]int{},&res)
    return res
}

func helper(nums []int,tmp []int,res *[][]int){
    if len(nums) == 0{
        //可以通过
        *res = append(*res,append([]int{},tmp...))
        return
    }
    
    for i := range nums{
        tmp = append(tmp,nums[i])
        Cnums := make([]int,len(nums)-1)
        copy(Cnums,nums[:i])
        copy(Cnums[i:],nums[i+1:])
        helper(Cnums,tmp,res)
        tmp = tmp[:len(tmp)-1]
    }
}

上面的方法中tmp的值是正确的

func permute(nums []int) [][]int {
    res := [][]int{}
    helper(nums,[]int{},&res)
    return res
}

func helper(nums []int,tmp []int,res *[][]int){
    if len(nums) == 0{
        //不可以通过
        *res = append(*res,tmp)
        return
    }
    
    for i := range nums{
        tmp = append(tmp,nums[i])
        Cnums := make([]int,len(nums)-1)
        copy(Cnums,nums[:i])
        copy(Cnums[i:],nums[i+1:])
        helper(Cnums,tmp,res)
        tmp = tmp[:len(tmp)-1]
    }
}

而这种tmp的值会有重复

diff

*res = append(*res,append([]int{},tmp...))

*res = append(*res,tmp)
阅读 2.1k
1 个回答
*res = append(*res,append([]int{},tmp...))

这个用 tmp 里面的元素重新生成了一个 slice 。

*res = append(*res,tmp)

这个是直接把 tmp 放进去了。

Slice:

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.

slice 这是一个描述符,复制描述符,并不会连带复制它下面的数组。于是,后一个方式,slice 背后的数组还会被继续使用,甚至被更改。

前一种方式,则是生成了一个全新的slice,连带一个全新的数组,所以就不会被后续更改了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题