/daily leetcode 3

permalink: /archive/posts/daily_leetcode_3/
date: Thu Sep 22 2022 00:00:00 GMT+0000 (Coordinated Universal Time)

78. Subsets

Medium

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.

Not a bad one today. You can pretty easily construct a powerset just by looping through your values and adding them to the previous subsets.

class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = [[]] # P(S) also contains null set
for i in nums:
result.extend([sset + [i] for sset in result])
return result

However, I found you can also do this much more functionally by abusing itertools' combinations function.

from itertools import combinations, chain

class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
return chain.from_iterable(
combinations(nums, i) for i in range(len(nums) + 1)
)

I think using libraries is a bit of a copout though. It's a bit strange that Leetcode allows them, however itertools is a part of the Python standard lib, so I guess there's no way around it.