From 2cb7abc616df46cae155d833a8088c9fe82f814a Mon Sep 17 00:00:00 2001 From: Deven <63876261+devenperez@users.noreply.github.com> Date: Thu, 19 Jan 2023 15:11:54 -0500 Subject: [PATCH] Time: 35 ms (80.56%), Space: 14.1 MB (33.36%) - LeetHub --- 78-subsets/78-subsets.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 78-subsets/78-subsets.py diff --git a/78-subsets/78-subsets.py b/78-subsets/78-subsets.py new file mode 100644 index 0000000..2870c1a --- /dev/null +++ b/78-subsets/78-subsets.py @@ -0,0 +1,29 @@ +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + + # All subsets can be mapped to a binary number where + # - the number is the same length as the list + # - a 1 represents the number being in the list, 0 otherwise + + # Example: nums = [1,2,3] + # subsetBinary = 0 = 0b000 -> [] + # = 3 = 0b011 -> [2, 3] + # (2 ** 3) - 1 = 7 = 0b111 -> [1, 2, 3] + + import math + powerSet = [] + + for subsetBinary in range(2 ** len(nums)): + subset = [] + + # Iterates exactly n times (where n is the number of 1s in the binary string) + while subsetBinary > 0: + indexOfFirst1 = -(math.floor(math.log2(subsetBinary)) + 1) + + subset.append(nums[indexOfFirst1]) + + subsetBinary -= 2 ** (-indexOfFirst1 - 1) + + powerSet.append(subset) + + return powerSet \ No newline at end of file