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
class Solution {
public:
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int previous = -1;
int current = -1;
for(int i=0;i<num.size()-1;i++)
{
if(num[i]<num[i+1])
{
previous = i;
}
}
if(previous!=-1)
{
for(int j=previous;j<num.size();j++)
{
if(num[previous]<num[j])
{
current = j;
}
}
swap(num[previous],num[current]);
sort(num.begin()+previous+1,num.end());//注意sort函数的用法
}
else
{
sort(num.begin(),num.end());//lowest possible order
}
}
};
本文介绍了一个C++函数,用于将一组整数排列成字典序中下一个更大的排列。如果不存在这样的排列,则将其调整为最小排列。该函数通过在输入数组中找到合适的元素进行交换来实现这一目标。
421

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



