[Leetcode 67] 31 Next Permutation

Problem:

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

 

Analysis:

First we need to find the first pair that A_i-1 < A_i, and then find the minimum element that is great than A_i-1 from A_i to A_end

swap A_i-1 and A_min_max.

at last, sort all the elements of A_i to A_end.

Then we can get the answer.

 

Code:

 1 class Solution {
 2 public:
 3     void nextPermutation(vector<int> &num) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int i, min_max;
 7         for (i=min_max=num.size()-1; i>0; i--) {
 8             if (num[i] > num[min_max])
 9                 min_max = i;
10             
11             if (num[i] > num[i-1])
12                 break;
13         }
14         
15         if (i == 0)
16             reverse(num.begin(), num.end());
17         else {
18             for (int j=i; j<num.size(); j++) {
19                 if (num[j] > num[i-1] && num[j] <= num[min_max])
20                     min_max = j;
21             }
22             
23             swap(num[i-1], num[min_max]);
24             
25             sort(num.begin()+i, num.end());
26         }
27     }
28     
29     void swap(int &a, int &b) {
30         int tmp = a;
31         a = b;
32         b = tmp;
33     }
34 };
View Code

 

posted on 2013-07-16 11:04  freeneng  阅读(165)  评论(0编辑  收藏  举报

导航