Describe your backtracking template. How do permutations, combinations, and subsets differ?
Backtracking questions are common and interviewer-friendly. One template handles most of them.
Template: at each decision point, try each valid choice → recurse → undo (pop). Always triple: "make choice / recurse / undo".
Subsets: include or exclude each element. 2^n outputs. Collect path at every node.
Combinations: like subsets but with size k constraint (skip branches where path.size > k, or limited by the start pointer).
Permutations: order matters. Maintain a used[] set or swap-in-place. n! outputs.
Pruning: sort input and skip duplicates, cutoff when remaining can't meet target (subset sum), bound cost against best-so-far.
One template: `void dfs(path, state) { if (terminal) { record path; return } for (choice in choices(state)) { apply(choice); dfs(path+choice, nextState); undo(choice); } }`. Subsets collect path every call (no terminal gate), permutations use a visited[] to skip used elements, combinations start the inner loop from i+1 instead of 0. For duplicates I sort input and skip `if i > start && nums[i]==nums[i-1]`. Pruning is what separates passing from TLE — in subset-sum I cut when path-sum already exceeds target; in N-queens I maintain diagonals in sets for O(1) validity check. The recursion tree shape tells me the worst case: 2^n for subsets, n! for permutations.
Always undo explicitly — easier to reason about than copying the path at every recurse.
Visited[] beats removing from list — O(1) vs O(n) per operation.
HireMe AI (即答侠) has one-page cheat sheets for subset/permutation/combination with duplicate-handling templates.
Backtracking IS DFS, with an explicit undo step so we can explore the next choice. DFS is the broader term.
Any time a monotonic bound proves the rest of a branch can't improve the best answer. Sorting input first often enables pruning.
HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.
Try HireMe AI Free