题目:
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 classSolution {2 public List> subsets(int[] nums) {3 List> res = new ArrayList>();4 Arrays.sort(nums);5 dfs(nums, 0, new ArrayList(), res);6 returnres;7 }8
9 private void dfs(int [] nums, int start, List item, List>res){10 res.add(new ArrayList(item));11 for(int i = start; i
AC Python:
classSolution:def subsets(self, nums: List[int]) ->List[List[int]]:
res=[]
self.dfs(nums, [], res)returnresdef dfs(self, nums: List[int], item: List[int], res: List[List[int]]) ->None:
res.append(item)for i inrange(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 classSolution {2 public List> subsets(int[] nums) {3 List> res = new ArrayList<>();4 res.add(new ArrayList());5 for(intnum : nums){6 //这里要注意,必须提前把size提取出来,不能把提取过程直接嵌入到下面的for语句中7 //因为res的size会在下面语句中一直变化
8 int size =res.size();9 for(int i = 0; i copyItem = new ArrayList(res.get(i));11 copyItem.add(num);12 res.add(copyItem);13 }14 }15
16 returnres;17 }18 }
AC Python:
classSolution:def subsets(self, nums: List[int]) ->List[List[int]]:
res=[[]]for num innums:for i inrange(len(res)):
res.append(res[i]+[num])return res