Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
class Solution {
public:
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int nSize = num.size();
if (nSize <= 1) return;
int idx = nSize - 1;
// 查找第一个下降的元素
while(--idx >= 0 && num[idx] >= num[idx+1]);
if (idx >= 0)
{
int i = nSize - 1;
// 查找第一个比idx所指元素大的元素
while(num[i] <= num[idx])
{
--i;
}
swap(num[i], num[idx]);
// 反转后面所有元素,让它从小到大sorted
reverse(num.begin()+idx+1, num.end());
}
else
{
reverse(num.begin(), num.end());
}
}
};