diff --git a/combination-sum.py b/combination-sum.py new file mode 100644 index 00000000..4942c88c --- /dev/null +++ b/combination-sum.py @@ -0,0 +1,21 @@ +# Time Complexity : O(N^target) +# Space Complexity : O(target) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + res = [] + def backtrack(remain, comb, start): + if remain == 0: + res.append(list(comb)) + return + elif remain < 0: + return + for i in range(start, len(candidates)): + comb.append(candidates[i]) + backtrack(remain - candidates[i], comb, i) + comb.pop() + backtrack(target, [], 0) + return res + \ No newline at end of file diff --git a/expression-add-operators.py b/expression-add-operators.py new file mode 100644 index 00000000..f8f1f46e --- /dev/null +++ b/expression-add-operators.py @@ -0,0 +1,30 @@ +# Time Complexity : O(4^N) +# Space Complexity : O(N) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +class Solution: + def addOperators(self, num: str, target: int) -> List[str]: + res = [] + n = len(num) + + def backtrack(index, path, value, prev): + if index == n: + if value == target: + res.append(path) + return + for i in range(index, n): + # Avoid numbers with leading zeros + if i != index and num[index] == '0': + break + curr_str = num[index:i+1] + curr = int(curr_str) + if index == 0: + backtrack(i+1, curr_str, curr, curr) + else: + backtrack(i+1, path + '+' + curr_str, value + curr, curr) + backtrack(i+1, path + '-' + curr_str, value - curr, -curr) + backtrack(i+1, path + '*' + curr_str, value - prev + prev * curr, prev * curr) + backtrack(0, '', 0, 0) + return res + \ No newline at end of file