小白求助，leetcode中寻找数列的所有子集的问题

lalalajiangbiyaosi · · 676 次点击 · 开始浏览    置顶

While iterating through all numbers, for each new number, we can either pick it or not pick it 1, if pick, just add current number to every existing subset. 2, if not pick, just leave all existing subsets as they are. We just combine both into our result. For example, {1,2,3} intially we have an emtpy set as result [ [ ] ] Considering 1, if not use it, still [ ], if use 1, add it to [ ], so we have [1] now Combine them, now we have [ [ ], [1] ] as all possible subset Next considering 2, if not use it, we still have [ [ ], [1] ], if use 2, just add 2 to each previous subset, we have [2], [1,2] Combine them, now we have [ [ ], [1], [2], [1,2] ] Next considering 3, if not use it, we still have [ [ ], [1], [2], [1,2] ], if use 3, just add 3 to each previous subset, we have [ [3], [1,3], [2,3], [1,2,3] ] Combine them, now we have [ [ ], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3] ] 由上所得代码： func main() { c := []int{3, 2, 4, 1} fmt.Println(subsets(c)) } func subsets(nums []int) [][]int { resu := make([][]int,1) for _,v := range nums { for _,rows := range resu { rows := append(rows,v) sort.Ints(rows) resu = append(resu,rows) } } return resu } Output: [[],[3],[2],[2,3],[4],[3,4],[2,4],[1,2,3],[1],[1,3],[1,2],[1,2,3],[1,4],[1,3,4],[1,2,4],[1,2,3,4]] Expected: [[],[3],[2],[2,3],[4],[3,4],[2,4],[2,3,4],[1],[1,3],[1,2],[1,2,3],[1,4],[1,3,4],[1,2,4],[1,2,3,4]] 其中有一组[1,2,3]和[2,3,4]不一致，发现在最后两次迭代过程中[2,3,4]变成了[1,2,3]。实在想不懂为什么。

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传