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,1
排序
本題要求當前排列的下一個排列,假設已是最大的排列,則對排列進行又一次排序,返回最小排列。ip
此題基本的方法是找規律:怎樣才幹獲得下一個排列?下一個排列有兩個特徵(暫未考慮已是最大的排列的狀況)it
要實現這個有三個步驟:
io
從低位依次比較A[i-1]與A[i],找到第一個A[i-1] <A[i] 交換A[i-1] 與其後大於A[i-1]的某位可以實現排列的增大。class
在A[i-1]以後的低位找到比A[i-1]大的最小的A[j],交換A[i-1]和A[j].file
交換了A[i-1]和A[j],就保證了排列會增大。對於A[i-1]後面的內容,進行從小到大排序就可以了。
方法
void nextPermutation(vector<int> &num) { //C++ for(int i = num.size()-1; i > 0 ; i-- ) { if(num[i] > num[i-1]) { int min = num[i] - num[i-1]; int pos = i; for(int k = i+1; k <num.size(); k++) { if(num[k] - num[i-1] < min && num[k] - num[i-1] >0) { min = num[k] - num[i-1]; pos = k; } } int tmp = num[pos]; num[pos] = num[i-1]; num[i-1] = tmp; sort(num.begin()+i,num.end()); return; } } sort(num.begin(),num.end()); }