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

LeetCode – Refresh – Next Permutation

时间:2015-03-21 11:00:51      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

 1 class Solution {
 2 public:
 3     void swap(int &a, int &b){int t = a; a = b; b = t;};
 4     void reverse(vector<int> &num, int start, int end) {
 5         int len = (end - start + 1)/2;
 6         for (int i = 0; i < len; i++) swap(num[start+i], num[end-i]);
 7     }
 8     void nextPermutation(vector<int> &num) {
 9         int len = num.size();
10         if (len < 2) return;
11         for (int i = len-2; i >= 0; i--) {
12             if (num[i] < num[i+1]) {
13                 for (int j = len-1; j > i; j--) {
14                     if (num[i] < num[j]) {
15                         swap(num[i], num[j]);
16                         break;
17                     }
18                 }
19                 reverse(num, i+1, len-1);
20                 return;
21             }
22         }
23         reverse(num, 0, len-1);
24     }
25 };

 

LeetCode – Refresh – Next Permutation

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4355172.html

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