78. subsets java_LeetCode 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],

[]

]

题解:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值