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 }

AC Python:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = []
        self.dfs(nums, [], res)
        return res
    
    def dfs(self, nums: List[int], item: List[int], res: List[List[int]]) -> None:
        res.append(item)
        for i in range(len(nums)):
            self.dfs(nums[i+1:], item + [nums[i]], res)

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 }

AC Python:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = [[]]
        for num in nums:
            for i in range(len(res)):
                res.append(res[i] + [num])
        return res

类似CombinationsCombination SumPalindrome PartitioningIncreasing Subsequences.

进阶题是Subsets II.

posted @ 2015-09-27 09:48  Dylan_Java_NYC  阅读(1243)  评论(0编辑  收藏  举报