[leetcode 31] Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code

The replacement must be in-place, do not allocate extra memory.blog

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排序

[Solution]it

採用字典排序法:io

1) 找到最大的k, 使得a[k] < a[k + 1], 此時a[k + 1], ..., a[n - 1]爲非增序
2) 對a[k + 1], ..., a[n - 1], 找到j, 使得j = min{a[i] > a[k] | i > k && i < n}, 交換a[k], a[j]
3) a[k + 1], ..., a[n - 1]從小到大排序, 由於已是非增序,直接首位連續交換便可.class

 1 void nextPermutation(vector<int> &num) 
 2     {
 3         int k = -1, j = -1, min = INT_MAX;
 4         
 5         for (int i = 0; i < num.size() - 1; i++)
 6             if (num[i] < num[i + 1])
 7                 k = i;
 8                 
 9         for (int index = k + 1; index < num.size(); index++)
10         {
11             if (num[index] > num[k] && num[index] <= min) /* 最後造成降序 */
12             {
13                 min = num[index];
14                 j = index;
15             }
16         }
17         
18         if (k != -1)
19             swap(num[k], num[j]);
20         for (int i = k + 1, l = num.size() - 1; i < l; i++, l--)
21             swap(num[i], num[l]);
22     }
相關文章
相關標籤/搜索