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);
        }
    }
  • 相关阅读:
    移动web开发之flex布局(弹性布局)
    移动web开发之流式布局
    移动端基础
    3D变形(CSS3) transform
    动画(CSS3) animation
    2D变形(CSS3) transform
    过渡(CSS3)
    CSS精灵技术(sprite)
    字体图标
    伸缩布局(CSS3)
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10076379.html
Copyright © 2011-2022 走看看