[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,1it

 1 // refer to http://bangbingsyb.blogspot.com/search?q=Next+Permutation
 2 class Solution {
 3 public:
 4     void nextPermutation(vector<int>& nums) {
 5         int i = 0, j = 0;
 6         
 7         if (nums.size() <= 1) return;
 8         
 9         for (i = nums.size() - 2; i >= 0; i--){
10             if (nums[i] < nums[i+1]){
11                 break;
12             }
13         }
14         
15         if (i < 0) {
16             sort(nums.begin(), nums.end());
17             return;
18         }
19         
20         j = i + 1;
21         while (j < nums.size() && nums[j] > nums[i]) j++;
22         j--;
23         
24         swap(nums[i], nums[j]);
25         sort(nums.begin() + i + 1, nums.end());
26         
27         return;
28     }
29 };
相關文章
相關標籤/搜索