diff --git a/combinationsum.py b/combinationsum.py new file mode 100644 index 00000000..63bac019 --- /dev/null +++ b/combinationsum.py @@ -0,0 +1,39 @@ +# the recursive function checks if the target is 0. If it is, it appends the path to the +# result and returns. If the target<0 or pivot == length of the caniddates, return. Else +# run a loop from pivot to the length of candidates. Add the number at the ith ind to the path +# and call the recursive function by subtracting the target. Pop the element from the list + +# Time complexity: O(2^m+n) +# Space: O(max(m,n)) + +class Solution(object): + + def combinationSum(self, candidates, target): + """ + :type candidates: List[int] + :type target: int + :rtype: List[List[int]] + + """ + self.result=[] + if not candidates: + return [] + else: + self.helper(candidates, target, [], 0) + return self.result + + + def helper(self, candidates, target, path, pivot): + + if target ==0: + self.result.append(path[:]) + return + if target<0 or pivot==len(candidates): + return + + for i in range(pivot, len(candidates)): + path.append(candidates[i]) + + self.helper(candidates, target-candidates[i], path,i) + + path.pop() \ No newline at end of file diff --git a/expressions-operations.py b/expressions-operations.py new file mode 100644 index 00000000..36426903 --- /dev/null +++ b/expressions-operations.py @@ -0,0 +1,43 @@ + +# If pivot is out of bounds and the calcualted exp==target, append the path to result. Else, return +# Run a loop from pivot to len of num. if i!=pivot and num[pivot] is 0, skip the loop. +# current will be the number between pivot and 1. When pivot is 0, call helper function where pivot is i+1 +# and path, calcualted and tail = current. +# Else, call recursively the helper function : + +# (num,target,i+1,path+"+"+str(current),calculated+current,current) for addition +# (num,target,i+1,path+"-"+str(current),calculated-current,-current) for sub +# (num,target,i+1,path+"*"+str(current),calculated-tail+(tail*current),tail*current) for multiplication + +# Time: O(4^n) +# Space: O(n) + + + +class Solution(object): + def addOperators(self, num, target): + """ + :type num: str + :type target: int + :rtype: List[str] + """ + self.result=[] + self.helper(num,target,0,'',0,0) + return self.result + + def helper(self, num, target, pivot, path, calculated, tail): + if pivot==len(num): + if calculated==target: + self.result.append(path) + return + for i in range(pivot, len(num)): + if i!=pivot and num[pivot]=='0': + continue + current=int(num[pivot:i+1]) + if pivot ==0: + self.helper(num,target,i+1,str(current),current,current) + else: + self.helper(num,target,i+1,path+"+"+str(current),calculated+current,current) + self.helper(num,target,i+1,path+"-"+str(current),calculated-current,-current) + self.helper(num,target,i+1,path+"*"+str(current),calculated-tail+(tail*current),tail*current) + \ No newline at end of file