Instagram
youtube
Facebook
Twitter

Subsets Leetcode Solution

In this tutorial, we are going to solve a leetcode problem, subsets in python.

Task:

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers of nums are unique.

Solution:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        lst = [[]] 
        
        for i in range(1,len(nums)+1):
            s = itertools.combinations(nums, i)
            for j in s:
                lst.append(list(j))
        
            
        return lst

Steps:

step1:  In this problem, first we declare a list that will contain lists of subsets.

step2:  Now, we will loop into the nums array from index 1 to len(nums) + 1.

step3: Now as per the advantage of python we'll be going to use the itertools function combination which will take an array and an integer i to return a list of subsets of size i.

step4: Then, we loop over the returned list from the itertools function and append it to our original lst list and after the loop, we return lst.