LeetCode题目之腾讯精选练习(50题):子集

野性酷女 2024-04-18 18:42 200阅读 0赞

题目

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例 :

  1. 输入: nums = [1,2,3]
  2. 输出:
  3. [
  4. [3],
  5. [1],
  6. [2],
  7. [1,2,3],
  8. [1,3],
  9. [2,3],
  10. [1,2],
  11. []
  12. ]

算法实现

  1. public IList<IList<int>> Subsets(int[] nums)
  2. {
  3. IList<IList<int>> list = new List<IList<int>>();
  4. list.Add(new List<int>());
  5. int len;
  6. for (int i = 0; i < nums.Length; i++)
  7. {
  8. len = list.Count;//记录要复制的元素数
  9. for (int j = 0; j < len; j++)//复制子集
  10. {
  11. list.Add(new List<int>(list[j]));
  12. }
  13. for (int k = len; k < list.Count; k++)//对后面复制的子集加入当前元素
  14. {
  15. list[k].Add(nums[i]);
  16. }
  17. }
  18. return list;
  19. }

执行结果

执行结果 : 通过
执行用时 : 368 ms, 在所有 C# 提交中击败了72.22%的用户
内存消耗 : 29.6 MB, 在所有 C# 提交中击败了6.67%的用户
在这里插入图片描述

小的总结

这道题对我来说有些困难,打算先找到规律,但是失败了,后来看了解题,知道了一种算是递归的方法,能够理解,并自己编了程序。后面的回溯法移植到c#上虽然成功,但稍有些不懂。

回溯法

  1. //回溯法
  2. private IList<IList<int>> res;
  3. private void find(int[] nums, int begin, IList<int> pre)
  4. {
  5. // 没有显式的递归终止
  6. res.Add(new List<int>(pre));// 注意:这里要 new 一下
  7. for (int i = begin; i < nums.Length; i++)
  8. {
  9. pre.Add(nums[i]);
  10. find(nums, i + 1, pre);
  11. pre.RemoveAt(pre.Count - 1);// 组合问题,状态在递归完成后要重置
  12. }
  13. }
  14. public IList<IList<int>> Subsets(int[] nums)
  15. {
  16. int len = nums.Length;
  17. res = new List<IList<int>>();
  18. if (len == 0)
  19. {
  20. return res;
  21. }
  22. IList<int> pre = new List<int>();
  23. find(nums, 0, pre);
  24. return res;
  25. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,200人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode 精选50--子集

    根据题意,找到几何中的所有子集,说实话子集是没有什么头绪的,因为如果采用遍历的方法,稍有遗漏不说,代码的嵌套循环层数随着数组大小的增加而增加,想了很久没有头绪后就去看了看评论,