12.22 2014
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
class Solution {
public:
void nextPermutation(vector<int> &num) {
int vio=num.size()-1;
while(vio>0){
if(num[vio-1]<num[vio])
break;
vio--;
}
if(vio>0){
vio--;
int change=num.size()-1;
while(change>=0 && num[change]<=num[vio])
change--;
swap(num[change],num[vio]);
vio++;
}
int end=num.size()-1;
int start=vio;
while(start<end){
swap(num[start], num[end]);
start++;
end--;
}
}
};
总结:
1. 从右到左,找出第一个不是递增的数,下标命名为vio;
2. 从右到左,找出第一个比该数大的数,下标命名为change,然后交换两者的值。
3. reverse下标为vio后面所有的值
出错点:
1. 没有理清算法,确定好要寻找的进位的地方
2. 为什么要reverse?因为是next greater permutation, 所以在进位以后,应该把所有数字从左到右递增增长,而第一步已经保证了从右到左是递增,所以只需要reverse即可。
3. 为何要vio--?因为找到的vio实际上是递增数列的最大值得位置。