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

    原题链接在这里:https://leetcode.com/problems/subsets/

    题目:

    Given a set of distinct integers, nums, return all possible subsets (the power set).

    Note: The solution set must not contain duplicate subsets.

    Example:

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

    题解:

    Set state on each level. What are needed for the state. 

    Here it needs to know index and current item.

    Time Complexity: exponential.

    Space: O(nums.length). stack space.

    AC Java:

     1 class Solution {
     2     public List<List<Integer>> subsets(int[] nums) {
     3         List<List<Integer>> res = new ArrayList<List<Integer>>();
     4         Arrays.sort(nums);
     5         dfs(nums, 0, new ArrayList<Integer>(), res);
     6         return res;
     7     }
     8     
     9     private void dfs(int [] nums, int start, List<Integer> item, List<List<Integer>> res){
    10         res.add(new ArrayList<Integer>(item));
    11         for(int i = start; i<nums.length; i++){
    12             item.add(nums[i]);
    13             dfs(nums, i+1, item, res);
    14             item.remove(item.size()-1);
    15         }
    16     }
    17 }

    Iteration时, 取res中现有list,每个list都加新的元素nums[i]然后再放回res中,同时保留原有list. 从[]开始一次加一个新元素。

    Note: 内层for loop 的size 一定要提前提取出来,不能在内层for中现提取,因为res的size一直在变.

    Time Complexity: exponential. Space: O(res.size()).

     AC Java:

     1 class Solution {
     2     public List<List<Integer>> subsets(int[] nums) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         res.add(new ArrayList<Integer>());
     5         for(int num : nums){
     6             //这里要注意,必须提前把size提取出来,不能把提取过程直接嵌入到下面的for语句中
     7             //因为res的size会在下面语句中一直变化
     8             int size = res.size();
     9             for(int i = 0; i<size; i++){
    10                 List<Integer> copyItem = new ArrayList<Integer>(res.get(i));
    11                 copyItem.add(num);
    12                 res.add(copyItem);
    13             }
    14         }
    15         
    16         return res;
    17     }
    18 }

    类似CombinationsCombination SumPalindrome Partitioning.

    进阶题是Subsets II.

  • 相关阅读:
    加密CMD使电脑溢出也拿不到CMD权限
    全面提升Linux服务器的安全
    ping 源码,详细解释
    伤心一百回
    聊聊我对黑客技术的思考
    一个网管员的真实成长经历
    通过命令限制上网用户的权限
    防范黑客的简单办法
    “黑客”人生
    黑客现身讲话
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4841881.html
Copyright © 2011-2022 走看看