代码改变世界

leetcode - Next Permutation

2013-11-10 10:33  张汉生  阅读(185)  评论(0编辑  收藏  举报

 

 1 class Solution {
 2 public:
 3     void nextPermutation(vector<int> &num) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         int n = num.size();
 6         if (n <= 1)
 7             return;
 8         int i;
 9         for (i = n - 2; i >= 0; i--){
10             if (num[i]<num[i + 1])
11                 break;
12         }
13         if (i < 0){
14             sort(num.begin(), num.end());
15             return;
16         }
17         int min = num[i + 1];
18         int minIndex = i + 1;
19         for (int j = i + 1 + 1; j<n; j++){
20             if (num[j]>num[i] && num[j]<min){
21                 min = num[j];
22                 minIndex = j;
23             }
24         }
25         int tmp = num[i];
26         num[i] = num[minIndex];
27         num[minIndex] = tmp;
28         sort(&num[i + 1], &num[n]);
29     }
30 };