#include <vector>
#include <iostream>
using namespace std;
static vector<vector<int>> res;
void dfs(vector<int>& choice, vector<int> path){
if(choice.empty()){
res.push_back(path);
return;
}
for(vector<int>::iterator iter = choice.begin(); iter != choice.end(); ++iter){
int tmp = *iter;
path.push_back(tmp);
choice.erase(iter++);
dfs(choice, path);
choice.insert(--iter, tmp);
path.pop_back();
}
}
void permute(vector<int>& arr){
vector<int> path;
dfs(arr, path);
}
int main(){
vector<int> arr = {1, 2,3};
permute(arr);
for(auto& path : res){
for(auto& i : path){
cout << i << " ";
}
cout << endl;
}
}
第二种写法:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
static vector<vector<int>> res;
void dfs(vector<int>& choice, vector<int> path, int n){
if(n == choice.size()){
res.push_back(path);
return;
}
for(vector<int>::iterator iter = choice.begin(); iter != choice.end(); ++iter){
auto tmp = find(path.begin(), path.end(), *iter);
if( tmp != path.end()){
continue;
}
path.push_back(*iter);
dfs(choice, path, n+1);
path.pop_back();
}
}
void permute(vector<int>& arr){
vector<int> path;
dfs(arr, path, 0);
}
int main(){
vector<int> arr = {1, 2, 3};
permute(arr);
for(auto& path : res){
for(auto& i : path){
cout << i << " ";
}
cout << endl;
}
}