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++; } } };