How to find next permutation
This is introduce how to find the next lexicographically permutation.
Suppose the permutation is 1 2 3
. The next one is 1 3 2
.
Algorithm in C++
C++ provide an algorithm called next_permutation
to support that. Reference
Example:
|
|
How it work.
There are four step to achieve.
- Find first decreasing element
A
in backward. - Find element
B
behindA
and just large thenA
. - Swap
A
andB
. - Reverse all elements behind
B
.
Why it works
Example each step
- Find the element that should be changed.
- Find the next element that will replace the previous one.
- Swap them.
- Since all elements behind the new one is decreasing, reverse them.