Skip to main content
←Architecture WorkspaceArchOSWorkspaces/
Sign in
ALGORITHM CANVAS · BACKTRACKING DFS · TIME O(N^(T/M)) · SPACE O(T/M)
Backtracking Recursion Tree & Branch Pruning
Sort candidates and break immediately when candidate > remaining target, pruning entire invalid subtrees before recursing.
ACTIVE CALL STACK (DEPTH 1) · REMAINING TARGET = 7START+2FOUND VALID COMBINATIONS (0):Exploring branches…
STEP 1/5 · L13
rem=7c=2path=[2]res=[]
PYTHON 3.12 · INSTANT PREVIEW
1def comb_sum(cands, target):
2 cands = sorted(cands)
3 res = []
4 path = []
5 def dfs(start, rem):
6 if rem == 0:
7 res.append(list(path))
8 return
9 for i in range(start, len(cands)):
10 c = cands[i]
11 if c > rem:
12 break
13 path.append(c)
14 dfs(i, rem - c)
15 path.pop()
16 dfs(0, target)
17 return res