31、Next Permutation
题目
这道题目的意思是给定一个序列,找出其按照字典顺序的下一个顺序,如果给定顺序是字典中的最后一个顺序,其下一个顺序则为字典中的第一个顺序。比如:
1,2,3,4,5-----注,后面的顺序去掉逗号
12354
12435
12453
12534
12543
13245
通过上面的例子可以发现规律,在得到13245序列时,其实是从12543的右往左做比较,如果左边比右边数字大,继续往左比较,直到左边数字比右边小,比如12543中,2的右边都是递增的,直到2比5小,因此在543中从右往左找到第一个比2大的数3,交换2,3得到13542,然后将3之后的数字从小到大排序就是所得序列,代码如下:
1 class Solution { 2 public: 3 void nextPermutation(vector<int>& nums) { 4 const int size = nums.size(); 5 int temp,left,right; 6 if(size <= 1) 7 return; 8 9 if(2 == size) 10 { 11 temp = nums[0]; 12 nums[0] = nums[1]; 13 nums[1] = temp; 14 return; 15 } 16 17 int index = size-1-1;//从倒数第二个开始 18 19 while (index>=0) 20 { 21 if(nums[index] >= nums[index + 1])//等号很重要,比如(5,1,1)的情况 22 index--; 23 else 24 break; 25 } 26 27 28 29 if(index>=0) 30 { 31 right = size - 1; 32 while(right > index) 33 { 34 if(nums[right] <= nums[index])//等号很重要,比如(5,1,1)的情况 35 right--; 36 else 37 break; 38 } 39 40 if(right>index) 41 { 42 temp = nums[right]; 43 nums[right] = nums[index]; 44 nums[index] = temp; 45 } 46 left = (++index); 47 } 48 else 49 left = 0; 50 51 right = size-1; 52 53 while (left <= right) 54 { 55 temp = nums[right]; 56 nums[right] = nums[left]; 57 nums[left] = temp; 58 left++; 59 right--; 60 } 61 62 } 63 };
原文:http://www.cnblogs.com/LCCRNblog/p/5041639.html