LeetCode | 60. Permutation Sequence——第K个全排列

82 篇文章 0 订阅
11 篇文章 0 订阅

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.

// 3 ms
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int multical(int n)     //阶乘函数
{
    if(n <= 1)
        return 1;
    return n*multical(n-1);
}

string getPermutation(int n, int k)     //n 位数字
{
    string res;
    int Index[10] = {};
    vector<char> Table;

    for(int i=1;i<=n;i++)   //初始化
        Table.push_back(i+'0');

    for(int i=0;i<n;i++)        //当前位的字符串,在Table中的位置
    {
        Index[i] = max(0,(k-1)/multical(n-i-1));    //不能为负数
        k -= (Index[i]*multical(n-i-1));
    }

    for(int i=0;i<n;i++)
    {
        res += Table[Index[i]];
        vector<char>::iterator it;
        for(it=Table.begin();it!=Table.end();it++)
        {
            if(*it == Table[Index[i]])
            {
                Table.erase(it);
                break;
            }
        }
    }


    return res;
}

int main()
{
    int n, k;
    while(cin>>n>>k)
    {
        cout<<getPermutation(n, k)<<endl;
    }
    return 0;
}

照惯例贴上solution区简短的代码

string getPermutation(int n, int k) {
    int i,j,f=1;
    // left part of s is partially formed permutation, right part is the leftover chars.
    string s(n,'0');
    for(i=1;i<=n;i++){
        f*=i;
        s[i-1]+=i; // make s become 1234...n
    }
    for(i=0,k--;i<n;i++){
        f/=n-i;
        j=i+k/f; // calculate index of char to put at s[i]
        char c=s[j];
        // remove c by shifting to cover up (adjust the right part).
        for(;j>i;j--)
            s[j]=s[j-1];
        k%=f;
        s[i]=c;
    }
    return s;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值