[LeetCode] Next Permutation

Well, in fact the problem of next permutation has been studied long ago. From the Wikipedia page, in the 14th century, a man named Narayana Pandita gives the following classic and yet quite simple algorithm (with minor modifications in notations to fit the problem statement):

  1. Find the largest index k such that nums[k] < nums[k + 1]. If no such index exists, the permutation is sorted in descending order, just sort it again in ascending order and we are done. For example, the next permutation of [3, 2, 1] is [1, 2, 3].
  2. Find the largest index l greater than k such that nums[k] < nums[l].
  3. Swap the value of nums[k] with that of nums[l].
  4. Reverse the sequence from nums[k + 1] up to and including the final elementnums[nums.size() - 1].

Quite simple, yeah? Now comes the following code, which is barely a translation.

Well, a final note here, the above algorithm is indeed powerful --- it can handle the cases of duplicates! If you have tried the problems Permutations and Permutations II, then the following function is also useful. Both of Permutations and Permutations II can be solved easily using this function. Hints: sort nums in ascending order, add it to the result of all permutations and then repeatedly generate the next permutation and add it ... until we get back to the original sorted condition. If you want to learn more, please visit this solution and that solution.

 1     void nextPermutation(vector<int>& nums) {
 2         int k = -1;
 3         for (int i = nums.size() - 2; i >= 0; i--) {
 4             if (nums[i] < nums[i + 1]) {
 5                 k = i;
 6                 break;
 7             }
 8         }
 9         if (k == -1) {
10             sort(nums.begin(), nums.end());
11             return;
12         }
13         int l = -1;
14         for (int i = nums.size() - 1; i > k; i--) {
15             if (nums[i] > nums[k]) {
16                 l = i;
17                 break;
18             } 
19         } 
20         swap(nums[k], nums[l]);
21         reverse(nums.begin() + k + 1, nums.end());
22     }
原文地址:https://www.cnblogs.com/jcliBlogger/p/4547978.html