我的问题是答案应该有 [1 1 2 2],但它得到了 [1 1 2 3]。我调试了这段代码,发现在那个循环中,首先将 [1 1 2 2] 附加到数组中,但在下一个循环中它更改为 [1 1 2 3]。我不明白为什么,以“D”开头的日志,这个数组中的元素在下一个循环中发生了变化。这是我的代码: https: //play.golang.org/p/X_CU8GlMOqfpackage mainimport ( "fmt")func main() { nums := []int{1, 1, 2, 2, 3} result := subsetsWithDup(nums) fmt.Println(result)}func subsetsWithDup(nums []int) [][]int { result := [][]int{{}, nums} for i := 0; i < len(nums); i++ { if i > 0 && nums[i] == nums[i-1] { continue } for j := 1; j < len(nums); j++ { result = append(result, dsf(nums, []int{nums[i]}, i+1, j)...) } } return result}func dsf(nums []int, set []int, start int, length int) [][]int { result := [][]int{} if len(set) == length { return append(result, set) } for i := start; i < len(nums); i++ { if i != start && nums[i] == nums[i-1] { continue } if len(set) == 3 { fmt.Printf("A %v %p\n", result, &result) } tmp := set[:] tmp = append(tmp, nums[i]) if len(set) == 3 { fmt.Printf("B %v %p %v %p\n", tmp, &tmp, result, &result) } result = append(result, dsf(nums, tmp, i+1, length)...) if len(tmp) == 4 { fmt.Printf("C %v %p %v %p\n", tmp, &tmp, result, &result) for _, r := range result { fmt.Printf("D %v %p\n", r, &r) } } } return result}A [] 0xc000004960B [1 1 2 2] 0xc0000049c0 [] 0xc000004960C [1 1 2 2] 0xc0000049c0 [[1 1 2 2]] 0xc000004960D [1 1 2 2] 0xc000004ae0A [[1 1 2 2]] 0xc000004960B [1 1 2 3] 0xc000004b60 [[1 1 2 3]] 0xc000004960C [1 1 2 3] 0xc000004b60 [[1 1 2 3] [1 1 2 3]] 0xc000004960D [1 1 2 3] 0xc000004ca0D [1 1 2 3] 0xc000004ca0A [] 0xc000004da0B [1 2 2 3] 0xc000004de0 [] 0xc000004da0C [1 2 2 3] 0xc000004de0 [[1 2 2 3]] 0xc000004da0D [1 2 2 3] 0xc000004f00
- 1 回答
- 0 关注
- 95 浏览
添加回答
举报
0/150
提交
取消