题目:
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
Solution:
思路,题目要求计算一个排列下一个字典排列。
从后往前,找到第一对非递减的相邻的两个数,然后再从后往前寻找比这小的数大的数,两者对调。在将小数后面的字符串反转即可。
代码更清晰:
void nextPermutation(vector<int>& nums)
{
vector<int>::iterator it = nums.end()-1;
while(it !=nums.begin())
{
if(*it > *(it-1)) //从后往前找到一个非递减的相邻数
{
vector<int>::iterator move_it = nums.end()-1;
while(move_it >= it)
{
if(*move_it > *(it-1))
{
swap(*move_it,*(it-1));
reverse(it,nums.end());
return;
}
move_it--;
}
}
it--;
}
reverse(nums.begin(),nums.end());
}