Next Permutation

来源:互联网 发布:软件系统可靠性分析 编辑:程序博客网 时间:2024/05/20 06:27

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


1.从后往前找到第一个正序对,记录正序对的第一个元素的下标为iMax

2.从后往前找到第一个大于num[iMax]的元素,下标记为jMax

3.交换num[iMax]与num[jMax]

4.将num[iMax]之后的元素翻转

5.将整个num翻转,得到最后结果

class Solution {public:    void nextPermutation(vector<int> &num) {        int iMax = -1;      for(int i = num.size() - 1;i >= 1;i--)          if(num[i-1] < num[i])              {                  iMax = i-1;                  break;              }      int jMax = -1;      for(int j = num.size() -1 ;j >= iMax;j--)          if(num[iMax] < num[j])              {                  jMax = j;                  break;              }           if(iMax != -1 and jMax != -1)     {        swap(num[iMax],num[jMax]);                reverse(num.begin()+iMax+1,num.end());    }        else        reverse(num.begin(),num.end());                    }};




0 0
原创粉丝点击