All lessonsOpen Open Open Open Open
5. Recursion
Backtracking intro
0 of 5 activities0%
Reading 1
Choose and revoke
Backtracking builds a solution step by step. If a partial choice fails constraints, undo (pop) and try another.
Examples: permutations, N-queens, subset generation, mazes.
Template: choose → recurse → un-choose.
void dfs(vector<int>& path) {
if (done) { save(); return; }
for (choice) {
path.push_back(choice);
dfs(path);
path.pop_back(); // undo
}
}Check 2
Undo
The un-choose step usually
Fill in 3
Name
Try it 4
Subsets of [1,2]
Print all subsets sizes.
main.cpp
Loading editor…
Output will appear here.
Assignment 5
Count subsets
Read n. Print 2^n (number of subsets of an n-element set).
main.cpp
Loading editor…