# 48ms Python solution (using itertools) with two other solutions

• 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 nums using 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.

class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def subsets(self, nums):
nums.sort()
res = []
for sz in range(len(nums) + 1):
combs = itertools.combinations(nums, sz)
for comb in combs:
res.append(list(comb))
return res

The following solutions are more desirable.

class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def subsets(self, nums):
nums.sort()
res = []
res.append([])
for num in nums:
n = len(res)
for idx in range(n):
temp = list(res[idx])
temp.append(num)
res.append(temp)
return res

class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def subsets(self, nums):
nums.sort()
num_subset = 2 ** len(nums)
res = [[]] * num_subset
for i in range(len(nums)):
for j in range(num_subset):
if j >> i & 1:
temp = list(res[j])
temp.append(nums[i])
res[j] = list(temp)
return res

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.