From bfd1d5c3df87567eec0acd8dd42dd621545d4efe Mon Sep 17 00:00:00 2001 From: spencerkrebs Date: Sat, 16 May 2026 16:01:03 -0400 Subject: [PATCH] a --- partition.py | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++ subsets.py | 35 +++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 partition.py create mode 100644 subsets.py diff --git a/partition.py b/partition.py new file mode 100644 index 00000000..df3d554b --- /dev/null +++ b/partition.py @@ -0,0 +1,62 @@ +# Time: O(n*2^n) - at every index the algorithm makes a binary choice (choose or no choose) - 2^n leaf nodes +# path + [nums[idx]] copies entire list into new list (n) + +# Space: O(n^2) because we create list copies at each recursive call, keep track of separate path lists + +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + self.result = [] + + def helper(idx,path): + if idx == len(nums): + self.result.append(path) + return + + # no choose + helper(idx+1,path) + + # choose + # + creates a brand new path, meaning left and right branches of tree look at diff spots in memory + helper(idx+1,path+[nums[idx]]) + + helper(0,[]) + return self.result + + +# Time: O(n*2^n) - at every index the algorithm makes a binary choice (choose or no choose) - 2^n leaf nodes +# path + [nums[idx]] copies entire list into new list (n) +# Space: O(n) with backtrack +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + self.result = [] + path =[] + def helper(idx): + if idx == len(nums): + self.result.append(path.copy()) + return + + # no choose + helper(idx+1) + # choose + path.append(nums[idx]) + helper(idx+1) + # backtrack + path.pop() + + helper(0) + return self.result + +# basic loop solution +# Time: O(n*2^n) +# space: O(n) +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + result=[[]] + for num in nums: + size = len(result) + for j in range(size): + temp = result[j][:] + temp.append(num) + result.append(temp) + + return result \ No newline at end of file diff --git a/subsets.py b/subsets.py new file mode 100644 index 00000000..e98290d6 --- /dev/null +++ b/subsets.py @@ -0,0 +1,35 @@ + +# for loop based recursion +class Solution: + def partition(self, s: str) -> List[List[str]]: + self.result = [] + + def helper(s,pivot,path): + if pivot == len(s): + self.result.append(list(path)) + return + + for i in range(pivot,len(s)): + # we keep track of substring between pivot and i + # whereas 0,1 recursion (without pivot) - for this problem we need 2 indices - so use for loop based recursion + subStr = s[pivot:i+1] + if isPalindrome(subStr): + # action + path.append(subStr) + # recurse + helper(s,i+1,path) + # backtrack + path.pop() + + def isPalindrome(s): + i = 0 + j = len(s)-1 + while i <= j: + if s[i] != s[j]: + return False + i+=1 + j-=1 + return True + + helper(s,0,[]) + return self.result \ No newline at end of file