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
32 changes: 32 additions & 0 deletions combination-sum.py
Original file line number Diff line number Diff line change
@@ -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
57 changes: 57 additions & 0 deletions expression-add-operators.py
Original file line number Diff line number Diff line change
@@ -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