码迷,mamicode.com
首页 > 其他好文 > 详细

Next Permutation

时间:2014-09-03 22:28:37      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   div   sp   log   

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

标签:style   blog   color   os   io   ar   div   sp   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3954557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!