【leetcode刷题笔记】Next Permutation

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 1,2,31,3,2
2 3,2,11,2,3
3 1,1,51,5,1

题解:字典序法

步骤:

1.从右向左找出第一个比它右边数字小的数,记为a;

2.找出a右边比它大的最小的数,记为b;

3.交换a和b;

4.reverse原来a所在位置后面所有的元素。

代码:

 1 class Solution {
 2 public:
 3     void nextPermutation(vector<int> &num) {
 4         int n = num.size();
 5         int j;
 6         for(j = n-2;j >= 0;j --){
 7             if(num[j] < num[j+1])
 8             {
 9                 //与右边比它大的最小的数互相换位
10                 int min_index = n-1;
11                 int minmum = 32767;
12                 for(int u = n-1;u > j;u --)
13                     if(num[u] > num[j]){
14                         if(num[u] < minmum){
15                             min_index = u;
16                             minmum = num[u];
17                         }
18                         break;
19                     }
20 
21                 char temp = num[min_index];
22                 num[min_index] = num[j];
23                 num[j] = temp;
24                 reverse(num.begin()+j+1,num.end());
25                 break;
26 
27             }
28         }
29         if(j < 0)
30             reverse(num.begin(),num.end());
31     }
32 };

有一种类似321这种序列的情况,它的下一个排列是123,字典序法是找不出来的,所以在代码29行单独加了一个判断,如果遇到这样的序列,直接倒置返回就可以了。

posted @ 2014-04-28 16:14  SunshineAtNoon  阅读(147)  评论(0编辑  收藏  举报