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

LeetCode--Next Permutation

时间:2014-09-10 22:25:01      阅读:271      评论:0      收藏:0      [点我收藏+]

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

 

(1)从后往前,找到a[i]<a[i+1]

(2)从i后面找到最小的比a[i]大的元素,交换(i后面的元素都是递减的,所以实现就看自己的了)

(3)将i后的元素reverse一下即可

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

 

LeetCode--Next Permutation

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

原文地址:http://www.cnblogs.com/cane/p/3965150.html

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