全排列
next_permutation
这里一般先用快排sort对原有数组进行排序
// next_permutation example
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort, std::reverse
using namespace std;
int main () {
int myints[] = {1,2,3};
sort (myints,myints+3);
cout << "The 3! possible permutations with 3 elements:\n";
do {
cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
} while ( next_permutation(myints,myints+3) );
cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
return 0;
}
输出
The 3! possible permutations with 3 elements:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3
prev_permutation
sort排序后用reverse进行翻转
// next_permutation example
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort, std::reverse
using namespace std;
int main () {
int myints[] = {1,2,3};
sort (myints,myints+3);
reverse (myints,myints+3);
cout << "The 3! possible permutations with 3 elements:\n";
do {
cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
} while ( prev_permutation(myints,myints+3) );
cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
return 0;
}
输出
3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3
After loop: 3 2 1
递归全排列
void perm(int arr[], int begin,int end){
{
//这里进行赋值或者输出操作
}
for(int j=begin;j<=end;j++){
swap(begin,j); //for循环将begin~end中的每个数放到begin位置中去
perm(arr,begin+1,end); //假设begin位置确定,那么对begin+1~end中的数继续递归
swap(begin,j); //换过去后再还原
}
}
例子
class Solution1 {
public:
vector<string> permutation(string S) {
vector<string> ret;
dfs(ret, 0, S);
return ret;
}
void dfs(vector<string>& ret, int index, string s) {
if (index >= s.size()) {
ret.push_back(s);
return;
}
for (int i = index; i < s.size(); ++i) {
swap(s[i], s[index]);
dfs(ret, index + 1, s);
swap(s[i], s[index]);
}
}
};
class Solution2 {
public:
vector<string> ans;
vector<string> permutation(string S) {
dfs(S, 0);
return ans;
}
void dfs(string S, int idx) {
int n = S.size();
if (idx == n) ans.emplace_back(S);
for (int i = idx; i != n; ++i) {
string tmp = S;
swap(tmp[idx], tmp[i]);
dfs(tmp, idx + 1);
}
}
};