class Solution:
# time O(2^N) space O(1)
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort() # I. this is optional, to optimize speed
def dfs(start,target,path):
if target < 0: # to optimize, can put this check in for loop and if condition applied, break (assuming sorted)
return
if target == 0:
res.append(path)
return
for i in range(start,len(candidates)):
#II. optimal solution2:
if target - candidates[i] < 0:
break
dfs(i,target-candidates[i],path+[candidates[i]])
dfs(0,target,[])
return res