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
42 changes: 42 additions & 0 deletions combination sum.py
Original file line number Diff line number Diff line change
@@ -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)
39 changes: 39 additions & 0 deletions expressions and operations.py
Original file line number Diff line number Diff line change
@@ -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