Skip to content
Open
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
77 changes: 77 additions & 0 deletions problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Time Complexity: 2 ^ n
# Space Complexity: O(h) -> height of the stack
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
def rec(i, target, path):
if target < 0 or i == len(candidates):
return
if target == 0:
res.append(path[:])
return

rec(i+1, target, path)
path.append(candidates[i])
rec(i, target - candidates[i], path)
path.pop()

rec(0, target, [])
return res

"""
# Time Complexity: 2 ^ n
# Space Complexity: O(h) -> height of the stack
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
def rec(pivot, target, path):
if target < 0 or pivot == len(candidates):
return
if target == 0:
res.append(path[:])
return

for i in range(pivot, len(candidates)):
# Action
path.append(candidates[i])

# Recurse

rec(i, target - candidates[i], path)

# Backtrack
path.pop()


rec(0, target, [])
return res

"""
# Time Complexity: 2 ^ n
# Space Complexity: O(h) -> height of the stack
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
def rec(pivot, target, path):
if target < 0 or pivot == len(candidates):
return
if target == 0:
res.append(path[:])
return

for i in range(pivot, len(candidates)):
# Action
path.append(candidates[i])

# Recurse

rec(i, target - candidates[i], path)

# Backtrack
path.pop()


rec(0, target, [])
return res

"""
43 changes: 43 additions & 0 deletions problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Space Complexity: O(h) -> height of stack
# Time Complexity: 4 ^ len(num)
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:

res = []

def helper(num, pivot, calc, tail, path, target, res):

if pivot == len(num):
if target == calc:
res.append(''.join(map(str, path)))
return

for i in range(pivot, len(num)):
if num[pivot] == '0' and i!=pivot: continue
curr = int(num[pivot:i+1])
if pivot == 0:
path.append(curr)
helper(num, i+1, curr, curr, path, target, res)
path.pop()
else:
# +
path.append('+')
path.append(curr)
helper(num, i+1, calc + curr, curr, path, target, res)
path.pop()
path.pop()
# -
path.append('-')
path.append(curr)
helper(num, i+1, calc - curr, -curr, path, target, res)
path.pop()
path.pop()
# *
path.append('*')
path.append(curr)
helper(num, i+1, calc - tail + tail * curr, tail*curr, path, target, res)
path.pop()
path.pop()

helper(num, 0, 0, 0, [], target, res)
return res