zoukankan      html  css  js  c++  java
  • 78. 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],
      []
    ]

    backtracking

    复杂度分析  https://www.1point3acres.com/bbs/thread-117602-1-1.html

    时间复杂度:还要考虑每一次要把tmp拷贝到res里的时间,复杂度是O(n)

    空间复杂度:call stack - O(n),存全部解集O(n * 2 ^ n),O(n) << O(n * 2 ^ n)

    time: O(n * 2^n), space: O(n * 2^n)

    class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            backtracking(nums, 0, new ArrayList<>(), res);
            return res;
        }
        
        private void backtracking(int[] nums, int idx, List<Integer> tmp, List<List<Integer>> res) {
            res.add(new ArrayList<>(tmp));
            for(int i = idx; i < nums.length; i++) {
                tmp.add(nums[i]);
                backtracking(nums, i + 1, tmp, res);
                tmp.remove(tmp.size() - 1);
            }
        }
    }

    time: O(2 ^ n), space: O(2 ^ n)

    class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            dfs(nums, 0, new ArrayList<>(), res);
            return res;
        }
        
        private void dfs(int[] nums, int idx, List<Integer> list, List<List<Integer>> res) {
            if(idx == nums.length) {
                res.add(new ArrayList<>(list));
                return;
            }
            
            list.add(nums[idx]);
            dfs(nums, idx + 1, list, res);
            list.remove(list.size() - 1);
            
            dfs(nums, idx + 1, list, res);
        }
    }
  • 相关阅读:
    websphere安装及部署
    ant的安装及使用
    JAVA多线程线程阻塞与唤醒
    Win2008 404 找不到文件或目录。
    cmd命令大全和IIS服务命令
    phpcgi.exe上传大量数据
    phpcgi.exe多个进程 ,cpu跑满
    php shopex显示乱码
    ie中td空值不显示边框解决办法
    Win2003服务器主机下无法/不能播放FLV视频的设置方法!
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10076379.html
Copyright © 2011-2022 走看看