Skip to content
Open

a #1266

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions partition.py
Original file line number Diff line number Diff line change
@@ -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
35 changes: 35 additions & 0 deletions subsets.py
Original file line number Diff line number Diff line change
@@ -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