首页 > 代码库 > 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,31,3,2

3,2,11,2,3

1,1,51,5,1

思路:首先,从后往前遍历,找到首次满足num[index]<num[index+1]的位置;然后,再次从后往前遍历,找到首次满足num[end]>num[index]的位置;交换num[index]和num[end],并将从index+1起始的后续序列逆序。

 1 class Solution { 2 public: 3     void nextPermutation( vector<int> &num ) { 4         int end = (int)num.size()-1, index = end-1; 5         while( index >= 0 && num[index] >= num[index+1] ) { --index; } 6         if( index == -1 ) { 7             reverse( num.begin(), num.end() ); 8             return; 9         }10         while( end > index && num[end] <= num[index] ) { --end; }11         swap( num[index], num[end] );12         reverse( num.begin()+index+1, num.end() );13         return;14     }15 };

 

Next Permutation