• 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);
        }
    }
  • 相关阅读:
    A Bug's Life(削弱版食物链)
    The Suspects
    Find The Multiple
    Lake Counting(dfs)
    经典dfs(depth-first search)
    喝啤酒(预防老年痴呆的深度搜索)
    C语言的位运算的优势 !
    Oil Deposits
    Catch That Cow
    HTML 003 元素
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10076379.html
Copyright © 2020-2023  润新知