码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Solution --- Next Permutation

时间:2015-06-02 23:26:30      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

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     }

 

LeetCode Solution --- Next Permutation

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4547978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!