Next Permutation

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;

    }

};

 

以上是关于Next Permutation的主要内容,如果未能解决你的问题,请参考以下文章

next_permutation 与 prev_permutation(全排列算法)

全排列 next_permutation() 函数的用法

hdu1716(库函数next_permutation)

LeetCode 31 Next Permutation(下一个全排列)

prev_permutation()和next_permutation()

Gym - 101020H Weekend floyd+next_permutation