Next Permutation

来源:互联网 发布:淘宝麻辣烫底料 编辑:程序博客网 时间:2024/05/29 15:13

ARRAY;

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

,抓住题目意思,正常是升序,升序之后渐渐的在后面降序,

首先找到::  需要交换的元素i,j。然后交换。 之后进行reverse。

其中::1,2,3.最后一个升序的,2,3将其交换就好

如 其他的,抓住最后一个升序的, 

  最后一个升序的小技巧,找到比后面小的数,然后找到最后一个大的数字。

class Solution {public:  void reversePart(vector<int>& nums,int k){int j=nums.size()-1;    int i=k+1;while(i<=j){swap(nums[i],nums[j]);           i++;   j--;}}void nextPermutation(vector<int>& nums){int flag=0;if(nums.size()==1)return;//find jint i=nums.size()-1;while (i>0&&nums[i-1]>=nums[i])//after is bigger.{i--;}int j=i;//difficult for me.while(j<nums.size()&&nums[j]>nums[i-1])j++;if(i==0)reversePart(nums,-1);else{swap(nums[i-1],nums[j-1]);reversePart(nums,i-1);}}};

如有不对的地方,请指正!

0 0
原创粉丝点击