Skip to content

Completed Backtracking-1 #1038

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
18 changes: 18 additions & 0 deletions combination_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Time Complexity: exponential
# Space Complexity: O(T/M)
class Solution:
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
result = []
self.combinationSumHelper([], 0, result, 0, target, candidates)
return result

def combinationSumHelper(self, current: list[int], start: int, result: list[list[int]], sum_val: int, target: int, candidates: list[int]):
if sum_val > target:
return
if sum_val == target:
result.append(current[:])
return
for i in range(start, len(candidates)):
current.append(candidates[i])
self.combinationSumHelper(current, i, result, sum_val + candidates[i], target, candidates)
current.pop()
35 changes: 35 additions & 0 deletions expression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Time Complexity: O(3^N * N)
# Space Complexity: O(N)

class Solution:
def addOperators(self, num: str, target: int) -> list[str]:
result = []
num_length = len(num)

def helper(start: int, expression: list[str], current_value: int, previous_value: int):
# Base case: if we've processed the entire number
if start >= num_length:
if current_value == target:
result.append("".join(expression))
return

# Handle the first number
if start == 0:
if num[start] == '0':
helper(start + 1, expression + ['0'], 0, 0)
else:
for i in range(start, num_length):
helper(i + 1, expression + [num[start:i + 1]], int(num[start:i + 1]), int(num[start:i + 1]))

# Handle subsequent numbers
else:
if num[start] == '0':
helper(start + 1, expression + ['+'] + ['0'], current_value, 0)
helper(start + 1, expression + ['-'] + ['0'], current_value, 0)
helper(start + 1, expression + ['*'] + ['0'], current_value - previous_value, 0)
else:
for i in range(start, num_length):
current_num = int(num[start:i + 1])
helper(i + 1, expression + ['+'] + [num[start:i + 1]], current_value + current_num, current_num)
helper(i + 1, expression + ['-'] + [num[start:i + 1]], current_value - current_num, -current_num)
helper(i + 1, expression + ['*'] + [num[start:i + 1]], current_value - previous_value + previous_value * current_num, previous_value