首页 > 代码库 > Next Permutation
Next Permutation
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
分析:得到一下个大一点的数可以通过下面四步:1)从右到左,找到第一个比其前一个小的数,记为pivot 2)从右到左找到第一个比pivot大的数,记作change 3)交换pivot和change的值 4)将pivot以后的数反序。代码如下:
1 class Solution { 2 public: 3 void nextPermutation(vector<int> &num) { 4 vector<int>::reverse_iterator pivot = next(num.rbegin()); 5 while(pivot != num.rend() && *pivot >= *prev(pivot))pivot++; 6 if(pivot == num.rend()) 7 reverse(num.begin(),num.end()); 8 else{ 9 vector<int>::reverse_iterator change = num.rbegin();10 while(*change <= *pivot)change++;11 swap(*pivot,*change);12 reverse(num.rbegin(),pivot);13 }14 }15 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。