class Solution {
public:
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (num.size() <= 1)
return;
int idx = num.size() - 2;
while (idx >= 0 && num[idx] >= num[idx + 1])
--idx;
if (idx >= 0)
{
int i = num.size() - 1;
while (num[i] <= num[idx])
--i;
swap(num[i], num[idx]);
reverse(num.begin() + idx + 1, num.end());
}
else
{
reverse(num.begin(), num.end());
}
}
};[Leetcode] Next Permutation
最新推荐文章于 2021-03-10 11:29:57 发布
本文介绍了一个C++实现的下一个排列算法,该算法用于找出整数序列中字典序上比当前序列更大的下一个排列。如果不存在这样的排列,则将序列重新排列成最小的字典序排列(即升序)。代码通过寻找第一个违反升序排序的元素,然后交换它与右侧大于它的最小元素来实现这一目标,并对剩余部分进行反转。
421

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



