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 };