From 1eba79f03734f48c4182b787eb21e2e41bfe2eff Mon Sep 17 00:00:00 2001 From: prenastro Date: Tue, 28 Jul 2026 02:18:10 -0700 Subject: [PATCH] Completed s30 Backtracking-1 --- combinationSum.py | 25 +++++++++++++++++++++++++ expressionAddOperators.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 combinationSum.py create mode 100644 expressionAddOperators.py diff --git a/combinationSum.py b/combinationSum.py new file mode 100644 index 00000000..a18eb282 --- /dev/null +++ b/combinationSum.py @@ -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) \ No newline at end of file diff --git a/expressionAddOperators.py b/expressionAddOperators.py new file mode 100644 index 00000000..3e180176 --- /dev/null +++ b/expressionAddOperators.py @@ -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) \ No newline at end of file