• 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;
    
        }
    
    };
  • 相关阅读:
    jquery另外一种类似tab切换效果
    简单的Tab切换组件
    switchable图片切换
    web前端性能优化总结
    iframe之间通信问题及iframe自适应高度问题
    javascript cookie
    grunt项目构建工具
    input全选与单选(把相应的value放入隐藏域去)
    Ajax跨域问题
    Jquery回到顶部功能
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5184241.html
Copyright © 2020-2023  润新知