Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
031. Next permutation (Medium)
links:
Title: https://oj.leetcode.com/problems/next-permutation/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Find the next permutation of a sequence.
Analysis:
Can be lazy with the ' next_permutation ' in STL.
The specific algorithm is:
First, from the end of the beginning to look forward to two adjacent elements, so that the first element is I, the second element is II, and meet i<ii ;
Then, from the end of the beginning to search forward, find the first element greater than I, set it to J;
Then, I and J are swapped, and then all elements of the II and later are reversed.
Code:
C++:
Class Solution {public: void Nextpermutation (vector<int> &num) {if (!num.size ()) Return;int idx = num.size ()-2;//1. Find out the last wrong orderwhile (idx >= 0 && num[idx] >= num[idx + 1]) idx--;//2. SWAPIF (idx >= 0) {int i = idx + 1;while (i < num.size () && num[i] > Num[idx]) i++;swap (num[i-1], Num[id x]);} 3. Reversereverse (Num.begin () + idx + 1, num.end ());}};
Python:
Class solution: # @param num, a list of integer # @return Nothing (void), does not return anything, modify Num IN-PL Ace instead. def nextpermutation (self, num): if not len (num): return idx = len (num)-2 # 1. "Find out" the last wrong or Der while idx >= 0 and Num[idx] >= Num[idx + 1]: idx-= 1 # 2. Swap If idx >= 0: i = idx + 1 While I < Len (num) and num[i] > Num[idx]: i + = 1 num[i-1], num[idx] = Num[idx], num[i-1] # 3. Reverse left , right = idx + 1, len (num)-1 and left <= right: Num[left], num[right] = Num[right], Num[left] Left + = 1 Right- = 1
[Leetcode] 031. Next permutation (Medium) (C++/python)