next_permutation
主要用于原地全排列的情况。
cppreference案例:
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
std::string s = "aba";
std::sort(s.begin(), s.end());
do {
std::cout << s << '\n';
} while(std::next_permutation(s.begin(), s.end()));
return 0;
}
输出
aab
aba
baa
面试题实战:数位重排
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
while(n--){
string str;
cin >> str;
int oldVal = stoi(str);
bool flag = false;
do{
int newVal = stoi(str);
if(oldVal != newVal && (oldVal % newVal == 0 || newVal % oldVal == 0)){
flag = true;
}
}while(next_permutation(str.begin(), str.end()));
cout << (flag ? "Possible" : "Impossible") << endl;
}
return 0;
}