我的問題是答案應(yīng)該有 [1 1 2 2],但它得到了 [1 1 2 3]。我調(diào)試了這段代碼,發(fā)現(xiàn)在那個循環(huán)中,首先將 [1 1 2 2] 附加到數(shù)組中,但在下一個循環(huán)中它更改為 [1 1 2 3]。我不明白為什么,以“D”開頭的日志,這個數(shù)組中的元素在下一個循環(huán)中發(fā)生了變化。這是我的代碼: 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 關(guān)注
- 105 瀏覽
添加回答
舉報
0/150
提交
取消