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;
        }
    };
  • 相关阅读:
    递推数列
    大数阶乘
    成绩排序
    DevC++ return 1 exit status
    POJ 1061 青蛙的约会
    ZOJ 2750 Idiomatic Phrases Game
    nyoj 545 Metric Matrice
    nyoj 308 Substring
    nyoj 515完全覆盖 II
    nyoj 1248 海岛争霸
  • 原文地址:https://www.cnblogs.com/tonix/p/3886239.html
Copyright © 2011-2022 走看看