zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    Hide Tags
     Backtracking Math
     
     

        这道题可以直接穷举然后数第k 个,或者 迭代k次得到返回值,或者直接计算出结果。我用是直接计算结果,很多细节上需要处理。
     
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Solution {
    public:
        string getPermutation(int n, int k) {
            if(n <2)    return "1";
            int tab[10]={1};
            for(int i =1;i<=9;i++)
                tab[i] = tab[i-1]*i;
            int remain[9]={0};
            for(int i=0;i<9;i++)
                remain[i]=i+1;
            int cnt = n;
            string ret = "";
            while(cnt>0){
                cnt--;
                int num = (k-1)/tab[cnt];
    //            cout<<"num="<<num<<endl;
                int idx = 0;
                while(remain[idx]==0)   idx++;
                for(int i=0;i<num;i++)
                    if(remain[++idx]==0)  i--;
    //            cout<<"idx="<<idx<<endl;
                ret += '0'+remain[idx];
                remain[idx]=0;
                k = k - num*tab[cnt];
    //            cout<<endl;
            }
            return ret;
        }
    };
    
    int main()
    {
        Solution sol;
        cout<<sol.getPermutation(9,213)<<endl;
        return 0;
    }
     
     
  • 相关阅读:
    Linux基础篇之软件源码包安装
    11-1 网络协议和管理
    bash-2 httpd服务的源码编译安装脚本
    8-1 文本三级剑客之sed
    9-3 磁盘存储与分区
    9-2 yum,dnf和apt
    9-1 软件包管理
    bash-1 初始化CentOS系统的初始化脚本
    3-3 man手册介绍
    5-3 文件权限
  • 原文地址:https://www.cnblogs.com/Azhu/p/4373535.html
Copyright © 2011-2022 走看看