Leetcode: Next Permutation, space
I. Question
This question provides a series of minimum numbers greater than this series.
For example:
1, 2, 3 → 1, 3, 2
3, 2, 1 → 1, 2, 3
1, 1, 5 → 1, 5, 1
Ii. Analysis
C ++-loving shoes may immediately think of the library function next_permutation (). That's right. In fact, this question is actually implemented (strictly speaking, it is only a preliminary implementation). If yes, if you directly enter this line of code, you can use:
void nextPermutation(vector<int> &num) { next_permutation( num.begin(), num.end() );}
However, it's not that we have ended like this. Of course we can't. We have to implement it ourselves. When we observe the sequence, we will find that if the sequence is decreasing, we cannot find a sequence that is larger than it, so we need to find two incrementing elements, that is, from right to left, find the first element on the left that is less than the right, and then find the smallest element on the right that is greater than the right of the element, swap two numbers, then, reverse () is followed by the number.
There are four steps:
1. from right to left, find the first element num [I] on the left that is less than the right.
2. Find the first element num [j] greater than num [I] from right to left.
3. Exchange num [I] And num [j];
4. reverse () after num [I ()
The Code is as follows:
class Solution {public: void nextPermutation(vector<int> &num) { int len = num.size()-1; int count = len-2; int i,j; for(i=len-1; i>=0; i--){ if(num[i+1]>num[i]){ for(j=len; j>i-1; j--){ if(num[j]>num[i]) break; } swap(num[i],num[j]); reverse(num.begin()+i+1,num.end()); return; } } reverse(num.begin(),num.end()); return; } void swap(int &a, int &b){ a = a + b;b = a - b;a = a - b; }};