1. When the Slice capacity is not enough, append will become a newly generated slice.
See the "pit" of filling in the append of golang slice - Zhihu (zhihu.com)
2. The result remains unchanged when appending
In question 46 of leetcode, my code is as follows
func permute(nums []int) [][]int {
if len(nums) == 0{
return [][]int{}
}
result := [][]int{}
track := []int{}
used := make([]bool, len(nums))
backtrack(nums, &track, &used, &result)
return result
}
func backtrack(nums []int, track *[]int, used *[]bool, result *[][]int){
// 触发结束条件
if len(*track) == len(nums){
temp := make([]int, len(*track))
copy(temp, *track) // 一定要copy到temp中再append,不能直接把*track append到*result中
*result = append(*result, temp)
return
}
for idx, num := range nums{
// 排除不合法的选择
if (*used)[idx]{
continue // nums[idx]已经做过选择
}
// 做选择
*track = append(*track, num)
(*used)[idx] = true
// 进入下一层决策树
backtrack(nums, track, used, result)
// 撤销选择
*track = (*track)[:len(*track)-1]
(*used)[idx] = false
}
return
}
In this code
My original intention is to append *track to *result, but the result of appending directly is wrong and the result remains unchanged. However, if I copy it and then append to *result, it will be correct, so it is obviously not the capacity of the first slice. At present, I haven’t found the reason yet, it’s already late at night, I’ll fill in the holes later when I find the reason.