Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa
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.blog
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
排序
这个题刚开始看我是懵的,由于之前没接触过全排序,不知道它要干吗,了解了全排序以后,其实就是交换数据,好比说须要交换第i和第j个元素(假设i<j),则交换完以后,第i+1及其以后的元素要进行重排序,使其递增;那么如今的问题就是找到要交换的元素,我所作就是从后往前查找:it
(1)好比如今要查倒数第k个元素,则从倒数第一个元素到倒数第k+1个元素进行顺序查找,若找到其中有一个元素的值大于倒数第k个元素的值,则进行交换,并在交换后按照上述方法排序。io
(2)若后面元素的值都比倒数第k个值小(或相等),则倒数第k个元素到倒数第一个元素造成一个非严格递减序列,则k--,继续(1);class
代码:方法
1 class Solution { 2 public: 3 void nextPermutation(vector<int>& nums) 4 { 5 if (nums.size()!=0) 6 { 7 int n=0,size=nums.size(); 8 for(int i=size-2;i>=0;i--) 9 { 10 int m=nums[i]; 11 for(int j=size-1;j>i;j--) 12 { 13 if (m<nums[j]) 14 { 15 nums[i]=nums[j]; 16 nums[j]=m; 17 n=1; 18 break; 19 } 20 } 21 if (n==1) 22 { 23 sort(nums.begin()+i+1,nums.end()); 24 break; 25 } 26 } 27 if (n==0) 28 { 29 for(int i=0;i<size/2;i++) 30 { 31 int m=nums[i]; 32 nums[i]=nums[size-i-1]; 33 nums[size-i-1]=m; 34 } 35 } 36 } 37 } 38 };