Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Backtracking

1 topic · 28 Nov 2026
1

Backtracking

Algorithm

Build a solution step by step; when a step cannot lead to a valid answer, undo it and try the next option.

All subsets (2^n) · C++
void subsets(vector<int> &a, int i, vector<int> &cur) {
    if (i == a.size()) {
        for (int x : cur) cout << x << " ";
        cout << "\n";
        return;
    }
    subsets(a, i + 1, cur);        // skip a[i]
    cur.push_back(a[i]);           // take a[i]
    subsets(a, i + 1, cur);
    cur.pop_back();                // undo
}
All permutations · C++
string s = "abc";
sort(s.begin(), s.end());
do cout << s << " "; while (next_permutation(s.begin(), s.end()));
// abc acb bac bca cab cba