Next PermutationFeb 25 '124235 / 11932
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,23,2,1 → 1,2,31,1,5 → 1,5,1
class Solution {
public:
void nextPermutation(vector<int> &num) {
int len = num.size();
for (int i = len - 1; i > 0; i--) {
if (num[i] > num[i-1]) {
int j = len - 1;
while (j > i - 1 && num[i-1] >= num[j]) j--;
swap(num[i-1], num[j]);
sort(num.begin() + i , num.end());
return;
}
}
sort(num.begin(), num.end());
}
};

本文介绍了一个C++函数nextPermutation,该函数接收一个整数向量并将其重新排列为字典序中下一个更大的排列。如果没有这样的排列,则将向量重新排列为最小的可能顺序(即升序)。此操作是在原地进行的,不会分配额外的内存。
417

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



