问题:
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
这道题要求我们求给定一列数的下一个全排列,而且是按字典顺序的。比如例子中的123,比123大的最小数是132,比115大的最小数是151,而321已经是最大的了,就输出最小值123。
经过观察,求最小的全排列数的方法如下:
从后往前迭代逐个数字a,值到找到这个数字a后面有比它大的数字b,就调换这两个数字的位置,再对原来数字a的位置后面的所有数字升序排序,得出的结果即为下一个全排列数。
如123,找到3比2大,就将这两个位置互换,再对原来2后面的所有数字进行排序(此处只有一位,不用排),得到结果132。
最后结果代码如下:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
//nums为空或只有一个数
if( nums.size() <= 1 ){
return ;
}
//判断是否是最大值,即看是否是降序
for( int i = 0 ; i < nums.size() ; i ++ ){
if( i > 0 && nums[i] > nums[i-1] ){
break;
}else if( i == nums.size() - 1 ){
sort( nums.begin() , nums.end() );
return ;
}
}
for( int i = nums.size() - 2 ; i >= 0 ; i-- ){
int flag = 0;
for( int j = nums.size() - 1 ; j > i ; j -- ){
if( nums[j] > nums[i] ){
int term = nums[j];
nums[j] = nums[i];
nums[i] = term;
sort( nums.begin() + i + 1, nums.end() );
flag = 1;
break;
}
}
if( flag == 1 ){
break;
}
}
}
};