Next Permutation
Question:
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).
The replacement must be in-place, do not allocate extra memory.
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
Solution:
1 class Solution { 2 public: 3 void nextPermutation(vector<int>& nums) { 4 int n=nums.size(); 5 int index=nums.size(); 6 for(int i=n-1;i>=1;i--) 7 { 8 if(nums[i]>nums[i-1]) 9 { 10 index=i-1; 11 break; 12 } 13 } 14 if(index!=nums.size()) 15 { 16 for(auto iter=nums.end()-1;iter>nums.begin()+index;iter--) 17 { 18 if(*iter>nums[index]) 19 { 20 int temp=nums[index]; 21 *(nums.begin()+index)=*iter; 22 *iter=temp; 23 break; 24 } 25 } 26 reverse(nums.begin()+index+1,nums.end()); 27 } 28 else 29 reverse(nums.begin(),nums.end()); 30 31 } 32 };