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
25 changes: 25 additions & 0 deletions combinationSum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def combinationSum(self, candidates, target):
self.result = []
self.helper(candidates, target, 0, [])
return self.result

def helper(self, candidates, target, pivot, path):
#base case
if target < 0 or pivot == len(candidates):
return

if target == 0:
self.result.append(list(path))
return

for i in range(pivot, len(candidates)):
#action
path.append(candidates[i])
#recurse
self.helper(candidates, target - candidates[i], i, path)
#backtrack
path.pop()

# TC - O(2 ^ (m+n)) where m is the candidates length and n is the target
# SC - O(n)
28 changes: 28 additions & 0 deletions expressionAddOperators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from typing import List
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
self.result = []

def helper(i, curr, calc, tail, path):
if i == len(num):
if calc == target and curr == 0:
self.result.append(path)
return

curr = curr * 10 + int(num[i])

if curr > 0:
helper(i + 1, curr, calc, tail, path)

if not path:
helper(i + 1, 0, curr, curr, path + str(curr))
else:
helper(i + 1, 0, calc + curr, curr, path + "+" + str(curr))
helper(i + 1, 0, calc - curr, -curr, path + "-" + str(curr))
helper(i + 1, 0, calc - tail + (tail * curr), tail * curr, path + "*" + str(curr))

helper(0, 0, 0, 0, "")
return self.result

# TC - O(4^n)
# SC - O(n)