題目連接html
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.函數
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.htm
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
blog
步驟以下:ip
class Solution { public: void nextPermutation(vector<int> &num) { int n = num.size(); if(n == 1)return; for(int i = n-2, ii = n-1; i >= 0; i--,ii--) if(num[i] < num[ii]) { int j = n-1; while(num[j] <= num[i])j--;//從尾部找到第一個比num[i]大的數,必定能夠找到 swap(num[i], num[j]); reverse(num.begin()+ii, num.end()); return; } reverse(num.begin(), num.end()); } };
STL中還提供了一個prev_permutation,能夠參考個人另外一篇博客:hereleetcode
【版權聲明】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3770126.htmlget