[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 gi...

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     }

 

目录
相关文章
|
8月前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
60 0
LeetCode 116. Populating Next Right Pointers
给定一颗二叉树,填充每一个节点的next指针使其指向右侧节点。 如果没有下一个右侧节点,则下一个指针应设置为NULL。
87 0
LeetCode 116. Populating Next Right Pointers
LeetCode 60. Permutation Sequence
集合[1,2,3,...,n]总共包含n的阶乘个独特的排列。
77 0
LeetCode 60. Permutation Sequence
LeetCode之Next Greater Element I
LeetCode之Next Greater Element I
89 0
LeetCode - 31. Next Permutation
31. Next Permutation Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个数列,求这个数列字典序的下一个排列.
830 0