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):
 
    "123"
    "132"
    "213"
    "231"
    "312"
    "321"
 
Given n and k, return the kth permutation sequence.
 
Note: Given n will be between 1 and 9 inclusive.

  分析:数学的思路来做。

复制代码
class Solution {
public:
    string getPermutation(int n, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int A[9] = {1,1, 2, 6, 24, 120, 720, 5040, 40320};
        string    res = "";
        vector<bool> flag(n+1, false);
        for(int i = n-1; i >= 0; --i)
        {
            int pos = k / A[i];
            if(k%A[i] ==0 && pos > 0) --pos;
            k = k - pos * A[i];
            for(int j = 1; j <= n; ++j)
            {
                if(flag[j] == false){
                    if(pos == 0)
                    {
                        char c = '0' + j;
                        res += c;
                        flag[j] = true;
                        break;
                    }else{
                        --pos;
                    }
                }
            }
        }

        return res;
    }
};
复制代码

 

posted @   冰点猎手  阅读(227)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· MQ 如何保证数据一致性?
· 《HelloGitHub》第 108 期
点击右上角即可分享
微信分享提示