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:
class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() result = [[]] for i in xrange(len(nums)): size = len(result) for j in xrange(size): result.append(list(result[j])) result[-1].append(nums[i]) return result
Python:
class Solution2(object): def subsets(self, nums): result = [] i, count = 0, 1 << len(nums) nums.sort() while i < count: cur = [] for j in xrange(len(nums)): if i & 1 << j: cur.append(nums[j]) result.append(cur) i += 1 return result
Python:
class Solution3(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ return self.subsetsRecu([], sorted(nums)) def subsetsRecu(self, cur, nums): if not nums: return [cur] return self.subsetsRecu(cur, nums[1:]) + self.subsetsRecu(cur + [nums[0]], nums[1:])
C++:
class Solution { public: vector<vector<int> > subsets(vector<int> &nums) { vector<vector<int>> result(1); sort(nums.begin(), nums.end()); for (size_t i = 0; i < nums.size(); ++i) { const size_t size = result.size(); for (size_t j = 0; j < size; ++j) { result.emplace_back(result[j]); result.back().emplace_back(nums[i]); } } return result; } };
类似题目:
[LeetCode] Subsets II 子集合 II