Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Build power set of set

Sharing is caring!

Problem statement
Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

Sample input

[1, 2, 3]

Sample output

[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]

Full code

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        power_set = []
        power_set.append([])
        for n in nums:
            new_power_set = []
            for subset in power_set:
                new_power_set.append(subset)
                new_subset = subset[:]
                new_subset.append(n)
                new_power_set.append(new_subset)
            power_set = new_power_set
            
        return power_set


def main():
    solution = Solution()
    print(solution.subsets([1,2,3]))

if __name__ == "__main__": main()