zoukankan      html  css  js  c++  java
  • Permutation Sequence(超时,排列问题)

    The set [1,2,3,…,n] contains a total of n! unique permutations.

    By listing and labeling all of the permutations in order,
    We get the following sequence (ie, for n = 3):

    1. "123"
    2. "132"
    3. "213"
    4. "231"
    5. "312"
    6. "321"

    Given n and k, return the kth permutation sequence.

    Note: Given n will be between 1 and 9 inclusive.

    Submission Result: Time Limit Exceede

    Last executed input: 9, 94626

    我的超时代码:

    class Solution {
    private:
        vector<vector<int>> res;
        int my_n;
        int my_k;
        bool overFlag;
    public:
        void swap(vector<int> &a,int i,int j){
            int temp=a[i];
            a[i]=a[j];
            a[j]=temp;
        }
        void dfs(int dep,vector<int> temp,vector<int> v)
        {
            if(dep==my_n){
                res.push_back(temp);
                if(res.size()==my_k) 
                    overFlag=false;
                return;
            }
            for (int i=dep;i<my_n&&overFlag;++i)
            {
                swap(v,dep,i);
                temp.push_back(v[dep]);
                dfs(dep+1,temp,v);
                temp.pop_back();
                swap(v,dep,i);
            }
        }
        string getPermutation(int n, int k) {
            overFlag=true;
    
            string resStr("");
            vector<int> v;
            my_n=n;
            my_k=k;
            for (int i=1;i<=n;++i)
            {
                v.push_back(i);
            }
            vector<int> temp;
            dfs(0,temp,v);
    
            vector<int> resV=res[k-1];
            for (int i=0;i<resV.size();++i)
            {
                resStr.push_back(resV[i]+'0');
            }
            return resStr;
        }
    };
  • 相关阅读:
    LintCode "Maximum Gap"
    LintCode "Wood Cut"
    LintCode "Expression Evaluation"
    LintCode "Find Peak Element II"
    LintCode "Remove Node in Binary Search Tree"
    LintCode "Delete Digits"
    LintCode "Binary Representation"
    LeetCode "Game of Life"
    LintCode "Coins in a Line"
    LintCode "Word Break"
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4136922.html
Copyright © 2011-2022 走看看