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
33 changes: 33 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#39. Combination Sum

from typing import List


class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
self.result=[]

self.helper(0, candidates, target, [])
return self.result


def helper(self, index, candidates, target, potentialCand):

if target==0:
self.result.append(potentialCand[:])
return

if index == len(candidates) or target<0:
return


#no choose:
self.helper(index+1, candidates, target, potentialCand)

#choose candidate
potentialCand.append(candidates[index])
self.helper(index, candidates, target-candidates[index], potentialCand)
potentialCand.pop()

sol = Solution()
print(sol.combinationSum([2], 1))
48 changes: 48 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# time complexity 4^n since we have 4 sub recursion paths at every number
# spac complexity -> On as we are saving only the digits in the pathlist array
# logic -> using pivot and i create the possible combinations of numbers and between every 2 numbers try all 3 operations

class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
result = []
digits = [int(d) for d in num]
def helper(pivot, pathList, calc, tail):
if pivot == len(num):
if calc == target:
result.append("".join(pathList))
curr = 0
for i in range(pivot, len(num)):
if digits[pivot] == 0 and pivot != i:
break
curr = curr*10 + digits[i]
currStrNum = num[pivot:i+1]
if pivot == 0:
pathList.append(currStrNum)
helper(i+1, pathList, curr, curr)
pathList.pop()
else:
#addition
pathList.append("+")
pathList.append(currStrNum)
helper(i+1, pathList, calc+curr, curr)
pathList.pop()
pathList.pop()


#subtraction
pathList.append("-")
pathList.append(currStrNum)
helper(i+1, pathList, calc-curr, -curr)
pathList.pop()
pathList.pop()


# multiply
pathList.append("*")
pathList.append(currStrNum)
helper(i+1, pathList, calc-tail+(tail*curr), (tail*curr))
pathList.pop()
pathList.pop()
helper(0, [], 0, 0,)
return result