一.问题描述
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
二.我的解题思路
首先要理解什么叫字典序排列,可参见博客:http://blog.youkuaiyun.com/zhutulang/article/details/7763810。
弄清楚什么叫字典序排列之后,这套题目就转换成了常见的数组问题,测试通过的程序如下:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int len=nums.size();
bool flag=0;int r=0;
//从数组的右侧开始寻找第一个nums[r-1]<nums[r]的数
for( r=len-1;r>0;r--){
if(nums[r-1]<nums[r]){
flag=1; break;
}
}
//需要按从小到大的顺序进行排列
if(flag==0){
reverse(nums,0,len-1);
}
else{
int curr_idx= r-1;
int min=nums[curr_idx+1];int min_idx=curr_idx+1;
for(int r=curr_idx+1;r<len;r++){
if(nums[r]>nums[curr_idx]){
if(nums[r]<=min){
min=nums[r];min_idx=r;
}
}
}
swap(nums[curr_idx],nums[min_idx]);
reverse(nums,curr_idx+1,len-1);
}
}
private:
void swap(int& a,int& b){
int tmp=0;
tmp=b;
b=a;
a=tmp;
}
void reverse(vector<int>& nums,int st,int end){
int tmp=0;
while(st<=end){
tmp=nums[st];
nums[st]=nums[end];
nums[end]=tmp;
st++;
end--;
}
}
};

本文介绍如何实现将一组数字重新排列成字典序中下一个更大的排列。若无法形成更大的排列,则将其排列为最小的顺序。提供了详细的解题思路及C++代码实现。
1万+

被折叠的 条评论
为什么被折叠?



