zoukankan      html  css  js  c++  java
  • LeetCode "Permutations"

    Lexicographically algorithms: 

    1. Iterate array from back to front, and find the first decreasing point:

       1,2,4,3 -- 4

    2. Iterate array from back to front, again to find the first number larger than the previous number of the found one in #1:

       1,2,4,3 -- 3

    3. Swap the found two:

       1,3,4,2

    4. Reverse all elems from found index in #1 to the end:

       1,3,2,4

    class Solution {
    public:
        
        vector<vector<int> > permute(vector<int> &num) {
            std::sort(num.begin(), num.end());
    
            vector<vector<int> > ret;
            ret.push_back(num);
    
            while(true)
            {
                vector<int> rlast = ret.back();
                //    Find decreasing item back->front
                int i;
                for(i = rlast.size() - 1; i > 0; i --)
                    if(rlast[i] > rlast[i-1]) break;                
                if(i == 0) break;
                int j = i - 1;
                int k;
                for( k = rlast.size() - 1; k > 0; k --)
                    if(rlast[k] > rlast[j]) break;
                std::swap(rlast[j], rlast[k]);
                std::reverse(rlast.begin() + i, rlast.end());
                ret.push_back(rlast);
            }
    
            return ret;
        }
    };
  • 相关阅读:
    打印机无法打印文件
    .Net com组件操作excel(不建议采用Com组件操作excel)
    Zebra
    Map遍历方式
    PageHelper原理
    MySQL8.0新特性
    算法_插入排序
    贝叶斯定理
    二叉树学习笔记
    Java校验时间段重叠
  • 原文地址:https://www.cnblogs.com/tonix/p/3886239.html
Copyright © 2011-2022 走看看