# Middle-题目88：31. Next Permutation

23人阅读 评论(0)

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>& nums) {
next_permutation(nums.begin(), nums.end());
}
};

12ms,beats 10.04%,众数12ms,88.95%
Cmershen的碎碎念：
C++11中，Next_permutation的源码如下：

    bool _Next_permutation(_BidIt _First, _BidIt _Last, _Pr _Pred)
{   // permute and test for pure ascending, using _Pred
_BidIt _Next = _Last;
if (_First == _Last || _First == --_Next)
return (false);

for (; ; )
{   // find rightmost element smaller than successor
_BidIt _Next1 = _Next;
if (_DEBUG_LT_PRED(_Pred, *--_Next, *_Next1))
{   // swap with rightmost element that's smaller, flip suffix
_BidIt _Mid = _Last;
for (; !_DEBUG_LT_PRED(_Pred, *_Next, *--_Mid); )
;
_STD iter_swap(_Next, _Mid);
_STD reverse(_Next1, _Last);
return (true);
}

if (_Next == _First)
{   // pure descending, flip all
_STD reverse(_First, _Last);
return (false);
}
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56369次
• 积分：3204
• 等级：
• 排名：第10668名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论