# missjing/leetcode

Switch branches/tags
Nothing to show
Fetching contributors…
Cannot retrieve contributors at this time
57 lines (52 sloc) 1.39 KB
 problem: 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、从后往前找严格升序对，记索引分别为i, j,如果未找到跳第4步 //2、找到后将索引i,j下的值交换 //3、i后面也全部为降序，因此需将这部分全部reverse //4、则整个序列都为降序，这个时候返回序列的升序，即把原序列reverse下 void swap(vector &num, int l, int r) { int tmp = num[l]; num[l] = num[r]; num[r] = tmp; } void reverse(int start, int end, vector &num) { while(start < end) { swap(num, start, end); start++; end--; } } void nextPermutation(vector &num) { if(num.size() <= 1) return; int l = num.size() - 2; int r = num.size() - 1; while(num[l] >= num[r]) { if(l + 1 == r) { l--; r = num.size() - 1; if(l < 0) break; } else r--; } if(l >= 0) swap(num, l, r); reverse(l+1, num.size() - 1, num); return; }