Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Python Solution
similar to Prime Products and all kinds of num combination problems:
class Solution:
# @param S, a list of integer
# @return a list of lists of integer
def subsets(self, S):
# Base result
result = [[]]
for num in S:
for element in result[:]:
x=element[:]
x.append(num)
result.append(x)
return result
Another way:
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = [[]]
for i in range(len(nums)):
k = nums[i]
res += map(lambda x:x+[k],res)
return res
let nums = [1,2,3]
First initialize res as empty list [[]], then pick the first element from nums, that is 1.
Then append 1 to all subsets in res, also append the original res to update current res, so res becomes[[],[1]],
then pick 2 from nums, res becomes[[],[1],[2],[1,2]].
Finally pick 3 from nums, res becomes [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]].
This can be done easily by lambda functions.
JavaScript Solution, inspired by the python one
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function(nums) {
var res = [[]];
nums.forEach(function(element) {
var clone = res.slice();
clone.forEach(function(list){
var x = list.slice();
x.push(element);
res.push(x);
});
});
return res;
};