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
orm
代碼以下:it
class Solution { public: void nextPermutation(vector<int>& nums) { //先從右往左掃描,找到最後一個從右往左的升序元素以前的位置 int pos = -1; for (int i=nums.size()-1; i>0; i--) { if (nums[i-1] < nums[i]) { pos = i - 1; break; } } if (pos == -1) //整個從右到左升序,那麼須要翻轉數組而後返回 { reverse(nums, 0, nums.size()-1); return; } //找到了最後一個升序元素nums[pos] //若是能在pos右邊找到一個比nums[pos]大的,那麼就和它交換 for (int i=nums.size()-1; i>pos; i--) { if (nums[i] > nums[pos]) { int temp = nums[pos]; nums[pos] = nums[i]; nums[i] = temp; break; } } reverse(nums, pos+1, nums.size()-1); } void reverse(vector<int>& nums, int start, int end) { if (nums.size()==0||nums.size()==1) { return; } if (start >= end) { return; } if (start < 0 || end >= nums.size()) { return; } int i = start; int j = end; while (j>i) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; j--; i++; } } };