mplement 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
本题在于如何分析转换的特性。当按照降序排列为最大,升序排列为最小。首先按照从右往左开始寻找不符合降序排列的数记为A,在A的右边区域寻找最小的大于A的数B,然后交换A,B,此时B的右边区域
仍然是降序排列,将右边区域转换为升序排列,则所求的数即为解。
代码如下:
class Solution {
public:
void swap(vector<int>& nums,int i,int j)
{
nums[i] = nums[i]^nums[j];
nums[j] = nums[i]^nums[j];
nums[i] = nums[i]^nums[j];
}
void reverse(vector<int>& nums,int start)
{
int i=start,j=nums.size()-1;
while(i<j)
{
swap(nums,i,j);
i++;
j--;
}
}
void nextPermutation(vector<int>& nums) {
int i=nums.size()-2;
while(i>=0 && nums[i+1] <= nums[i])
i--;
if(i>=0)
{
int j = nums.size()-1;
while(j>i && nums[j] <= nums[i])
j--;
swap(nums,i,j);
}
reverse(nums,i+1);
}
};