zoukankan      html  css  js  c++  java
  • [LeetCode] 78. Subsets

    Given an integer array nums of unique elements, return all possible subsets (the power set).

    The solution set must not contain duplicate subsets. Return the solution in any order.

    Example 1:

    Input: nums = [1,2,3]
    Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
    

    Example 2:

    Input: nums = [0]
    Output: [[],[0]]

    Constraints:

    • 1 <= nums.length <= 10
    • -10 <= nums[i] <= 10
    • All the numbers of nums are unique.

    子集。

    给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

    解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

    思路还是回溯,而且模板要背下来。第八行的sort被省略是因为78题没有重复元素,然后之后的90题有重复元素,这一行排序就用得上了。递归函数的一开始,将子数组加入结果集,然后遍历input,注意遍历的时候不是从0开始,而是从start index开始。

    时间O(2^n) - 因为最后就是有2^n个结果

    空间O(n)

    Java实现

     1 class Solution {
     2     public List<List<Integer>> subsets(int[] nums) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         // corner case
     5         if (nums == null || nums.length == 0) {
     6             return res;
     7         }
     8         // Arrays.sort(nums);
     9         helper(res, new ArrayList<>(), nums, 0);
    10         return res;
    11     }
    12 
    13     private void helper(List<List<Integer>> res, List<Integer> list, int[] nums, int start) {
    14         res.add(new ArrayList<>(list));
    15         for (int i = start; i < nums.length; i++) {
    16             list.add(nums[i]);
    17             helper(res, list, nums, i + 1);
    18             list.remove(list.size() - 1);
    19         }
    20     }
    21 }

    LeetCode 题目总结

  • 相关阅读:
    python笔记之条件语句、循环语句、迭代器和生成器
    浅谈IO和NIO
    浅谈java自定义类加载器
    浅谈Synchronized和ReentrantLock
    软工1816 · 第三次作业
    软工1816 · 第二次作业
    软工1816 · 第一次作业
    简单的自我介绍
    The Last
    第七次课程作业
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12710022.html
Copyright © 2011-2022 走看看