Skip to content

[78] Subsets

https://leetcode.com/problems/subsets/description/

  • algorithms
  • Medium (49.01%)
  • Source Code: 78.subsets.py
  • Total Accepted: 350.6K
  • Total Submissions: 673.5K
  • Testcase Example: '[1,2,3]'

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],   [] ]

python
class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        result = []
        if not nums: return result

        self.helper(nums, 0, [], result)
        return result

    def helper(self, nums, i, current, result):
        if i == len(nums):
            result.append(current[:])
            return
        else:
            self.helper(nums, i+1, current, result)
            current.append(nums[i])
            self.helper(nums, i+1, current, result)
            current.pop(-1)
#
#
# s = Solution()
# print s.subsets([1, 2, 3])

Last updated: