diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..f756fc4c --- /dev/null +++ b/Problem1.py @@ -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)) \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..1846db7d --- /dev/null +++ b/Problem2.py @@ -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 +