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)
这个用 tmp 里面的元素重新生成了一个 slice 。
这个是直接把 tmp 放进去了。
Slice:
slice 这是一个描述符,复制描述符,并不会连带复制它下面的数组。于是,后一个方式,slice 背后的数组还会被继续使用,甚至被更改。
前一种方式,则是生成了一个全新的slice,连带一个全新的数组,所以就不会被后续更改了。