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

Next Permutation

时间:2015-07-09 00:31:20      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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

Solution:

 1 class Solution {
 2 public:
 3     void nextPermutation(vector<int>& nums) {
 4     int n=nums.size();
 5     int index=nums.size();
 6     for(int i=n-1;i>=1;i--)
 7     {
 8         if(nums[i]>nums[i-1])
 9         {
10             index=i-1;
11             break;
12         }
13     }
14     if(index!=nums.size())
15     {
16         for(auto iter=nums.end()-1;iter>nums.begin()+index;iter--)
17         {
18             if(*iter>nums[index])
19             {
20                 int temp=nums[index];
21                 *(nums.begin()+index)=*iter;
22                 *iter=temp;
23                 break;
24             }
25         }
26         reverse(nums.begin()+index+1,nums.end());
27     }
28     else
29         reverse(nums.begin(),nums.end());
30         
31     }
32 };

技术分享

Next Permutation

标签:

原文地址:http://www.cnblogs.com/riden/p/4631534.html

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