diff --git a/combination sum.py b/combination sum.py new file mode 100644 index 00000000..4b305d97 --- /dev/null +++ b/combination sum.py @@ -0,0 +1,42 @@ +#repeatition allowed +#for loop based recursion: +#when amount <0: go back and go to second baby +#after all current babies are done ie for loop is complete,we will go back to previous functional call's next baby.. done with all babies ie completed for loop... go to previous.... +#keep track of paths and if amount ==0: add that path to result list +#logic: 1)action 2)recurse 3)backtrack the action +#logic: 1)action with new li 2)recurse with new li +class Solution: + def combinationSum(self,candidates,target): + res = [] + def helper(pivot,target,path): + #1 base ie return and boundary conditions + if target==0: + res.append(list(path)) #append deepcopy of the path + return + if target<0: + return + if pivot==len(candidates): + return + + #2 logic + for i in range(pivot,len(candidates)): + #action + path.append(candidates[i]) + + #recurse + helper(i,target-candidates[i],path) + + #backtrack + path.pop() + + helper(0,target,[]) + return res + + # #2 logic + # for i in range(pivot,len(candidates)): + # #action + # li = list(path) ie deep copy everytime to avoid backtracking the action + # li.append(candidates[i]) + + # #recurse + # helper(i,target-candidates[i],li) diff --git a/expressions and operations.py b/expressions and operations.py new file mode 100644 index 00000000..3960e963 --- /dev/null +++ b/expressions and operations.py @@ -0,0 +1,39 @@ +#for strings also look for edge case 0s +#for operations on strings always look for * operation and use tail*curr condition + +class Solution: + def addOperators(self, num: str, target: int) -> List[str]: + res =[] + + def helper(pivot,calc_val,tail,path,target): + #base + if pivot == len(num): #we are at leaf ie all digits are done + if calc_val==target: + res.append(path) + return + + #logic + for i in range(pivot,len(num)): + #preceeding 0 edge case eg 105: 05 will be number with pivot at 0 but i at 5 and int will convert "05" to int 5. to avoid that + if num[pivot] == '0' and i != pivot: + break + #1 action + curr = int(num[pivot:i+1]) #1st we get 1, 12, 123 numbers from "123" ie from pivot to i + if pivot==0: #no operators problems ie top level ie 1, 12, 123 + helper(i+1,curr,curr,path+str(curr),target) + + else: # operators are present + #2 recurse + #+ + helper(i+1,curr+calc_val,curr,path+"+"+str(curr),target) + + #- + helper(i+1,-curr+calc_val,-curr,path+"-"+str(curr),target) + + #* + #3 backtrack only for *, we backtrack the last addition using tail and recalculate properl + helper(i+1, calc_val-tail+tail*curr, tail*curr, path+"*"+str(curr), target) + + + helper(0,0,0,"",target) + return res