Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

Let's understand the Backtracking algorithm

Backtracking algorithm

Introduction:

Source code

Version 1

Idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#define N 3

using namespace std;

void backtracking(string& s, string& res, bool *c){
if(res.length() == N){
cout << res << endl;
return;
}
for(int i = 0; i < N; ++i){
if(c[i] == 0){
res.push_back(s[i]);
c[i] = 1;

backtracking(s, res, c);

c[i] = 0;
res.pop_back();
}
}
}

int main(){
string s = "ABC", res = "";
bool c[N] = {0};
backtracking(s, res, c);
return 0;
}