首页 > 代码库 > Next Permutation

Next Permutation

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 

分析:得到一下个大一点的数可以通过下面四步:1)从右到左,找到第一个比其前一个小的数,记为pivot 2)从右到左找到第一个比pivot大的数,记作change 3)交换pivot和change的值 4)将pivot以后的数反序。代码如下:

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