Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code
The replacement must be in-place, do not allocate extra memory.blog
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
it
分析:獲得一下個大一點的數能夠經過下面四步:1)從右到左,找到第一個比其前一個小的數,記爲pivot 2)從右到左找到第一個比pivot大的數,記做change 3)交換pivot和change的值 4)將pivot之後的數反序。代碼以下:io
1 class Solution { 2 public: 3 void nextPermutation(vector<int> &num) { 4 vector<int>::reverse_iterator pivot = next(num.rbegin()); 5 while(pivot != num.rend() && *pivot >= *prev(pivot))pivot++; 6 if(pivot == num.rend()) 7 reverse(num.begin(),num.end()); 8 else{ 9 vector<int>::reverse_iterator change = num.rbegin(); 10 while(*change <= *pivot)change++; 11 swap(*pivot,*change); 12 reverse(num.rbegin(),pivot); 13 } 14 } 15 };