Created
June 1, 2015 00:46
-
-
Save phg1024/407d299f85ded4054748 to your computer and use it in GitHub Desktop.
Sample implementation of next permutation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
using namespace std; | |
template <typename Container> | |
bool nextperm(Container &s) { | |
using T = Container; | |
typename T::iterator first = s.begin(); | |
typename T::iterator last = s.end() - 1; | |
typename T::iterator i = last; | |
typename T::iterator ii = i; | |
--i; | |
while( *ii < *i && i >= first) { | |
--i; | |
ii = i+1; | |
} | |
if( ii == first ) { | |
std::reverse(ii, s.end()); | |
return false; | |
} | |
typename T::iterator j = last; | |
while( *j < *i ) { | |
--j; | |
} | |
std::swap(*i, *j); | |
std::reverse(ii, s.end()); | |
return true; | |
} | |
int main(int argc, char **argv) { | |
string s; | |
cin >> s; | |
std::sort(s.begin(), s.end()); | |
// now output the permutations | |
cout << "v1:" << endl; | |
bool flag = true; | |
while( flag ) { | |
flag = nextperm(s); | |
cout << s << endl; | |
} | |
cout << "v2:" << endl; | |
std::sort(s.begin(), s.end()); | |
flag = true; | |
while( flag ) { | |
flag = next_permutation(s.begin(), s.end()); | |
cout << s << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment