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

lalalajiangbiyaosi · · 960 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

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]。实在想不懂为什么。

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

960 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传