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).spa
The replacement must be in-place, do not allocate extra memory.code
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
以上方法中,最壞狀況須要掃描數組三次,因此時間複雜度是O(3*n)=O(n),空間複雜度是O(1)。代碼以下:it
1 class Solution { 2 public: 3 void nextPermutation(vector<int> &num) { 4 5 int n=num.size(); 6 int i,j; 7 for(i=n-2;i>=0;i--) 8 { 9 if(num[i]<num[i+1]) 10 { 11 break; 12 } 13 } 14 if(i>=0) 15 { 16 for(j=i+1;j<n;j++) 17 { 18 if(num[j]<=num[i]) 19 { 20 break; 21 } 22 } 23 j--; 24 swap(num[i],num[j]); 25 } 26 27 reverse(num.begin()+i+1,num.end()); 28 } 29 30 31 void swap(int &a,int &b) 32 { 33 int tmp=a; 34 a=b; 35 b=tmp; 36 } 37 };