以下是一道子集回溯递归的题目,打印每次设置进结果的 list 发现,最后两个结果指针地址一致? 请问大家遇见过么。为什么会这样
func main() {
subsets([]int{3, 2, 4,1})
}
func subsets(nums []int) [][]int {
var result [][]int
subsetsRecursion(nums, 0, []int{}, &result)
fmt.Println(result)
return result
}
func subsetsRecursion(nums []int, n int, list []int, result *[][]int) {
// 终止条件
if n == len(nums) {
//temp := make([]int,len(list))
//copy(temp,list)
//*result = append(*result, temp)
*result = append(*result, list)
fmt.Printf("%p,%d,%d\n",list,n,list)
return
}
subsetsRecursion(nums, n+1, list, result)
list = append(list, nums[n])
subsetsRecursion(nums, n+1, list, result)
}
打印结果:
0x119f3e0,4,[]
0xc00012a008,4,[1]
0xc00012a028,4,[4]
0xc00012a040,4,[4 1]
0xc00012a058,4,[2]
0xc00012a070,4,[2 1]
0xc00012a090,4,[2 4]
0xc000138020,4,[2 4 1]
0xc00012a0c0,4,[3]
0xc00012a0d0,4,[3 1]
0xc00012a0f0,4,[3 4]
0xc000138040,4,[3 4 1]
0xc00012a130,4,[3 2]
0xc000138060,4,[3 2 1]
## 以下两个地址居然相同?
0xc000138080,4,[3 2 4]
0xc000138080,4,[3 2 4 1]
[[] [1] [4] [4 1] [2] [2 1] [2 4] [2 4 1] [3] [3 1] [3 4] [3 4 1] [3 2] [3 2 1] [3 2 4] [3 2 4 1]]