Next Permutation

来源:互联网 发布:我知天下事手抄报 编辑:程序博客网 时间:2024/05/01 09:19

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

思路:其实我觉得这是一道数学题,需要总结规律。序列的下一个序列的规律如下:从右向左找到非递增的那个数的索引。例如1 3 5 4 2,索引i=2,然后从i向右遍历,找到索引j,满足: 索引j+1所对应的值小于i对应的值。即j=4,将i与j的值对调,然后将i+1...n的数值互调。代码如下:

class Solution {public:    void swap(int &a, int &b) {        a ^= b;        b ^= a;        a ^= b;    }    void nextPermutation(vector<int> &num) {        if (num.empty() || num.size() == 1) {            return;        }        vector<int> res;        res.clear();        int len = num.size();        res.resize(len);        int i,j;        for(i=len-2; i>=0; i--) {            if(num[i] < num[i+1]) {                break;            }        }        if(i < 0) {            for(j=0; j<len; ++j) {                res[j] = num[len-j-1];             }            num = res;        }        else {            for(j=i+1; j<len; ++j) {                if(num[j] <= num[i]) {                    break;                }            }            j = (j == len ? len-1 : j-1);            swap(num[i],num[j]);            int L,R;            for(L=i+1,R=len-1; L<R; ++L,--R) {                swap(num[L],num[R]);            }        }    }};


0 0
原创粉丝点击