Backtracking builds a solution one decision at a time. At each step it chooses an option, explores recursively, and un-chooses (backtracks) if the path fails. It prunes any partial solution that cannot succeed, which makes it far faster than checking every combination. Typical problems: subsets, permutations, mazes, Sudoku, N-Queens.
Remember
solve(state):
if state is a solution: report it; return
for each option:
if option is valid:
choose it
solve(next state)
undo it /* backtrack */
Reference
Cheat Sheet
Keep these facts handy while you work with Backtracking Basics in C.
#include <stdio.h>
static void solve(const int a[], int n, int start, int target, int chosen[], int cnt) {
if (target == 0) {
for (int i = 0; i < cnt; i++) {
if (i) printf(" ");
printf("%d", chosen[i]);
}
printf("\n");
return;
}
for (int i = start; i < n; i++) {
if (a[i] > target) continue;
chosen[cnt] = a[i];
solve(a, n, i + 1, target - a[i], chosen, cnt + 1);
}
}
int main(void) {
int a[] = {1, 2, 3}, chosen[3];
solve(a, 3, 0, 3, chosen, 0);
return 0;
}
Output
1 2
3
How It Works
Choosing 1 leaves a target of 2, and then 2 completes the sum, printing "1 2".
After choosing 1, the number 3 is skipped because it exceeds the remaining 2.
Starting with 2 then 3 fails to reach 3; starting with 3 matches immediately.
Edge Cases & Pitfalls
Check these before relying on Backtracking Basics in real programs.
undo
Forgetting to undo state
Shared state (like a visited array) must be restored after the recursive call.
prune
No pruning
Without early rejection, backtracking degrades to brute force.
Remember
Key Takeaways
Choose, explore, undo.
Prune early.
State must be restored.
One line: Backtracking builds a solution one decision at a time.
Frequently Asked Questions
A recursive technique that tries choices step by step and abandons a path as soon as it cannot lead to a valid solution.
Backtracking prunes partial solutions early instead of generating every complete candidate.
Continue with "Generating Permutations in C" next. Generate every ordering of an array by swapping and backtracking. The C Recursion and Backtracking hub lists every topic in order.