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;
        }
    };
  • 相关阅读:
    JS连接数据库“实例”
    sql数据字典
    硬件防火墙的配置
    xxx
    rhs属性文件删除法
    思科pix防火墙配置实例大全
    SilverLight中的画刷小结
    数据库表间的连接总结
    导入Excel到Sql Server 2005 (转)
    关于Silverlight页面跳转的总结
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4136922.html
Copyright © 2011-2022 走看看