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 and use only constant 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,23,2,1 → 1,2,31,1,5 → 1,5,1
class Solution {
public:
void swap(int & a, int &b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
void nextPermutation(vector<int>& nums) {
if(nums.size()<=1)
return ;
int i = nums.size()-1;
for(;i>0;i--)
{
if(nums[i]>nums[i-1])
break;
}
cout<<i<<endl;
int j=nums.size()-1;
for(; j>i-1&&i!=0; j--)
{
if(nums[j]>nums[i-1])
break;
}
if(i!=0)
{
swap(nums[j], nums[i-1]);
}
int start = i==0? 0 : i;
int end = nums.size()-1;
cout<<start<<":"<<end<<endl;
while(start<end)
{
int temp = nums[start];
cout<<temp<<endl;
nums[start] = nums[end];
nums[end] = temp;
start++;
end --;
}
}
};
本文介绍了一个C++实现的nextPermutation函数,该函数用于将一组数字重新排列为字典序中下一个更大的排列。若无法实现这样的排列,则将其变为最小的排列(升序)。文章通过示例展示了如何在原地修改输入的整数数组,并且只使用常量额外内存。
603

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



