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

原理参考:http://blog.csdn.net/qq575787460/article/details/41215475

class Solution {
public:
    void swap(int &a, int &b) {
        int tmp = a;
        a = b;
        b = tmp;
    }
    void reverse(vector<int> &s, int i, int j) {
        while (i < j) {
            swap(s[i], s[j]);
            i++;
            j--;
        }
    }
/*
 * 非递归的判断,:
 * 1.从右往左找到第一个比左边的数大的数a[j],a[j+1] a[j+1] > a[j]
 * 2.从a[j+2] 开始 找到第一个比a[j]大的数a[k]
 * 3.替换a[j], a[k]
 * 4.翻转 j+1 后面的内容
 * */
    int nextPermutation(vector<int> &s) {
        int j = s.size() - 1;

        while (j && s[j-1] >= s[j]) {
            j--;
        }
        if (0 == j) {
            reverse(s, 0, s.size()-1);
            return -1;
        }
        j--;
        int k = s.size() - 1;
        while (s[k] <= s[j]) {
            k--;
        }
        swap(s[j], s[k]);
        reverse(s, j+1, s.size()-1);
        return 0;

    }

};
原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5184241.html