Permutations
StopSearch tree
- CH1 path
53/53
Try every unused number at each place, and free it again on the way back.
Step through it →Backtracking builds an answer one choice at a time and undoes each choice to try the next, so it walks every branch of a tree of choices.
Each choice is appended just before its call and popped just after the call returns. So when a call runs, the path holds its own choices and nothing left over from a sibling.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
Recursing with i + 1 instead of i would allow 2 only once and miss [2, 2, 2, 2].
Try every unused number at each place, and free it again on the way back.
Step through it →Recurse from the same index to reuse a candidate, and stop once one is too big.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
def subsets(nums): result = [] path = [] def backtrack(start): result.append(path[:]) for i in range(start, len(nums)): path.append(nums[i]) backtrack(i + 1) path.pop() backtrack(0) return result