diff --git a/combination-sum.py b/combination-sum.py new file mode 100644 index 00000000..50ad6a20 --- /dev/null +++ b/combination-sum.py @@ -0,0 +1,32 @@ +# Time Complexity: O(2^(m+n)) +# Space Complexity: O(m+n) +# Did this code successfully run on Leetcode : Yes + +class Solution(object): + def combinationSum(self, candidates, target): + """ + :type candidates: List[int] + :type target: int + :rtype: List[List[int]] + """ + res=[] + path=[] + + def helper(pending_target,i,path): + #base + if pending_target<0 or i==len(candidates): + return + + if pending_target==0: + res.append(list(path)) + return + + #logic + helper(pending_target,i+1,path) + + path.append(candidates[i]) + helper(pending_target-candidates[i],i,path) + path.pop() + + helper(target,0,path) + 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..57e7652c --- /dev/null +++ b/expression-add-operators.py @@ -0,0 +1,57 @@ + +# Time Complexity: O(4^N) +# Space Complexity: O(N) +# Did this code successfully run on Leetcode : Yes + +class Solution(object): + def addOperators(self, num, target): + """ + :type num: str + :type target: int + :rtype: List[str] + """ + res=[] + N=len(num) + path=[] + def helper(pivot,calc,tail): + #base + if pivot==N: + if calc==target: + res.append(''.join(path)) + return + #logic + + for i in range(pivot,N): + if num[pivot]=='0' and pivot!=i: + break + + curr=int(num[pivot:i+1]) + if pivot==0: + path.append(str(curr)) + helper(i+1,curr,curr) + path.pop() + # path.pop() + else: + #+ + path.append('+') + path.append(str(curr)) + helper(i+1,calc+curr,curr) + path.pop() + path.pop() + + #- + path.append('-') + path.append(str(curr)) + helper(i+1,calc-curr,-curr) + path.pop() + path.pop() + + #* + path.append('*') + path.append(str(curr)) + helper(i+1,calc-tail+tail*curr,tail*curr) + path.pop() + path.pop() + + helper(0,0,0) + return res \ No newline at end of file