【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,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

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

仔细分析排列的特征,发现如下方法:

从后往前扫描。找到第一个“打破递增”的位置,下一个排列中该位置元素将被后面的递增序列中,大于其原始值的最小元素所取代。然后,把后半部分的元素排序(原本已经有序,只需要反转即可)。如图:

来源:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html

原文地址:https://www.cnblogs.com/dengeven/p/3607427.html