GuoXin Li's Blog

full permutation with backtracking

字数统计: 148阅读时长: 1 min
2021/01/14 Share

1, 2, 3 full permutation example in conventional “for circle” full permutation.

image-20210114195633990

with vector path.

image-20210114195922265

then backtracking method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
using namespace std;
void fun(int level, vector<int>&path ){
if(level == path.size()){
for(int num:path){
cout<<num<<" ";
}
cout <<endl;
return;
}
for(path[level] = 1; path[level] <= path.size(); path[level]++){
// before enter into next layer decision tree,
// checking whether path contains item contained or not.
// std::count: Returns the number of elements in the range [first,last) that compare equal to val.
if( count(path.begin(), begin(path) + level, path[level] ) != 0 ) continue;
fun(level+1, path);
}
}
int main() {
vector<int> path(4);
fun(0, path);
return 0;
}

reference: https://www.youtube.com/watch?v=nrHTtjkYEyQ

CATALOG