LeetCode

Next Permutation

2013.12.7 05:14

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

Solution:

  First of all, if a sequence is non-increasing, we can't find any of its permutations greater than itself. Then let's see this example.

    this: [3, 5, 4, 2, 1] -> next: [4, 1, 2, 3, 5]

    this: [3 5, 1, 2, 4] -> next: [3, 5, 1, 4, 2]

  A non-increasing sequence doesn't have a greater "next-permutation", so we'll have to find the first position where it is increasing, namely "3, 5" in sample 1, and "2, 4" in sampe 2.

  Take the first case for example, "3 5" is the first increasing position, we pick out "4", which is the first element greater than "3" from the right side, and do a swap:

    [3, 5, 4, 2, 1]->[4, 5, 3, 2, 1]

  Then reverse the part after "4":

    [3, 5, 4, 2, 1]->[4, 5, 3, 2, 1]->[4, 1, 2, 3, 5]

  You might wanna ask:

    1. Why check the right part? It's for lexicological order.

    2. Why choose the first element "4" that is greater than that "3"? To ensure it's the next greater permutation.

  Still, if the sequence is non-increasing at all, just reverse it to get the smallest permuation as the answer.

  Time complexity is O(n), space complexity is O(1).

Accepted code:

 1 // 1WA, 1AC
 2 class Solution {
 3 public:
 4     void nextPermutation(vector<int> &num) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         int i, j, n;
 8         int tmp;
 9         
10         n = num.size();
11         // 1WA here, wrong direction of $i
12         i = n - 2;
13         while(i >= 0 && num[i] >= num[i + 1]){
14             --i;
15         }
16         
17         if(i == -1){
18             reverse(num, 0, n - 1);
19             return;
20         }
21         
22         j = n - 1;
23         while(num[i] >= num[j]){
24             --j;
25         }
26         tmp = num[i];
27         num[i] = num[j];
28         num[j] = tmp;
29         
30         reverse(num, i + 1, n - 1);
31     }
32 private:
33     void reverse(vector<int> &num, int left, int right) {
34         int tmp;
35         int i;
36         
37         if(left >= right){
38             return;
39         }
40         
41         i = left;
42         while(i < left + right - i){
43             tmp = num[i];
44             num[i] = num[left + right - i];
45             num[left + right - i] = tmp;
46             ++i;
47         }
48     }
49 };
原文地址:https://www.cnblogs.com/zhuli19901106/p/3462409.html