LeetCode:Next Permutation

题目连接html

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).code

The replacement must be in-place, do not allocate extra memory.htm

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1blog


步骤以下:ip

  • 从最尾端开始往前寻找两个相邻的元素,二者知足i < ii(令第一个元素为i,第二个元素为ii)
  • 若是没有找到这样的一对元素则,代表当前的排列是最大的,没有下一个大的排列
  • 若是找到,再从末尾开始找出第一个大于i的元素,记为j                                  本文地址
  • 交换元素i, j,再将ii后面的全部元素颠倒排列(包括ii)
  • 若是某个排列没有比他大的下一个排列(即该排列是递减有序的),调用这个函数仍是会把原排列翻转,即获得最小的排列
class Solution {
public:
    void nextPermutation(vector<int> &num) {
        int n = num.size();
        if(n == 1)return;
        for(int i = n-2, ii = n-1; i >= 0; i--,ii--)
            if(num[i] < num[ii])
            {
                int j = n-1;
                while(num[j] <= num[i])j--;//从尾部找到第一个比num[i]大的数,必定能够找到
                swap(num[i], num[j]);
                reverse(num.begin()+ii, num.end());
                return;
            }
        reverse(num.begin(), num.end());
    }
};

 

STL中还提供了一个prev_permutation,能够参考个人另外一篇博客:hereleetcode

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3770126.htmlget

相关文章
相关标签/搜索