码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Subsets

时间:2015-06-03 00:51:30      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

Well, this problem becomes fairly easy once we use the itertools package of Python. It is just a transformation of the type of the result. And other things are already done by itertools.

The idea is to create a list res. Then generate subsets of size 0, 1, ..., len(nums) of numsusing the combinations method of itertools, and transform them to list (originally tuple) and then append them to res.

Of course, this is not a meaningful solution and this problem does not aim at testing whether we know how to use itertools. The key idea still lies at backtracking.

 1 class Solution:
 2     # @param {integer[]} nums
 3     # @return {integer[][]}
 4     def subsets(self, nums):
 5         nums.sort() 
 6         res = []
 7         for sz in range(len(nums) + 1):
 8             combs = itertools.combinations(nums, sz)
 9             for comb in combs:
10                 res.append(list(comb))
11         return res 

The following solutions are more desirable.

 1 class Solution:
 2     # @param {integer[]} nums
 3     # @return {integer[][]}
 4     def subsets(self, nums):
 5         nums.sort() 
 6         res = []
 7         res.append([])
 8         for num in nums:
 9             n = len(res)
10             for idx in range(n):
11                 temp = list(res[idx])
12                 temp.append(num)  
13                 res.append(temp)
14         return res
15 
16 class Solution:
17     # @param {integer[]} nums
18     # @return {integer[][]}
19     def subsets(self, nums):
20         nums.sort()
21         num_subset = 2 ** len(nums)
22         res = [[]] * num_subset
23         for i in range(len(nums)):
24             for j in range(num_subset):
25                 if j >> i & 1:
26                     temp = list(res[j]) 
27                     temp.append(nums[i])
28                     res[j] = list(temp)
29         return res

 

[LeetCode] Subsets

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4548112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!