Subsets LeetCode Solution

Subsets LeetCode

Quoestion: For the given set find all unique subsets i.e,powerset


For Example:

set = [1,2,3]

powerset=[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Approach:

1.intialize powerset with empty List

2.Add 1st element ([[],[1]])

3.Add 2nd element and add possible unique combinations of 1st and 2nd elements.([[],[1],[2],[1,2]])

4.repeat above step until size of powerset is 2^n

5.return Powerset


Python Code:

class Solution(object):

    def subsets(self, nums):

        powerset=[[]]

        n = len(nums)

        if n == 0:

            return powerset

        for i in nums:

            for j in range(len(powerset)):

                print(len(powerset))

                temp = powerset[j]+[i]

                powerset.append(temp)

        return powerset

Python One Liner:

from itertools import chain, combinations

class Solution(object):

    def subsets(self,nums):

        temp = list(nums)

        return chain.from_iterable(combinations(temp, i) for i in range(len(nums)+1))

  

Try Problem in LeetCode




    



Post a Comment

0 Comments