码迷,mamicode.com
首页 > 其他好文 > 详细

Next Permutation

时间:2016-02-06 18:26:44      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5184241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!