leetcode 60. 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.


解析:

方法一:会超时!!!

通过STL中next_permutation(begin, end);来算下一个全排列。
理论上你要算n个数的第k个排列只要调用k-1次next_permutation()
但是一般来说肯定会超时的,因为next_permutation的时间复杂度是O(n)。所以如果用这个的话时间复杂度是O(NK)。

//只是写写思路,参考一下,leetcode不能运行
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    vector<int> v{1,2,3,4,5};
    int i = 1;
    while (i <= 16)
    {
        next_permutation(v.begin(),v.end());
        ++i;
    }
    for (auto i : v)
        cout << i;
    system("pause");
    return 0;
}

方法二:

康托展开的公式

X=an*(n-1)!+an-1*(n-2)!+...+ai*(i-1)!+...+a2*1!+a1*0!

适用范围:没有重复元素的全排列

举例来说:

康托展开O(n)

题目:找出第16个n = 5的序列(12345)

首先第十六个也就是要前面有15个数,要调用15次next_permutation函数。

根据第一行的那个全排列公式,15 / 4! = 0 …15 =>
有0个数比他小的数是1,所以第一位是1

拿走刚才的余数15,用15 / 3! = 2 …3 =>
剩下的数里有两个数比他小的是4(1已经没了),所以第二位是4

拿走余数3, 用 3 / 2! = 1 …1 =>
剩下的数里有一个数比他小的是3,所以第三位是3

拿走余数1, 用 1/ 1! = 1 …0 =>
剩下的数里有一个数比他小的是 5(只剩2和5了),所以第四位是5

所以排列是 1,4,3,5,2

class Solution {
public:
//全排列剖析:求n个数第k个排序----康托展开
//http://blog.csdn.net/modiziri/article/details/22389303?utm_source=tuicool&utm_medium=referral
    string getPermutation(int n, int k) {
        int i=1;
        string input,res;
        while(i<=n)
        {
             input+=i+'0';
             ++i;
        }
        //要求第k个排列,之前有k-1个。quot=k-1;
        int quot=k-1,reminder=0;
        for(int i=n-1;i>0;--i)
        {
            reminder=quot%fact(i);
            quot=quot/fact(i);
            res+=min_x(input,quot);
            quot=reminder;
        }
        res+=input;
        return res;
    }
    int fact(int temp){
        int res=1;
        for(int i=1;i<=temp;++i)
        {
            res*=i;
        }
        return res;
    }
    char min_x(string &in,int x){
        char res=in.at(x);
        in.erase(in.begin()+x);
        return res;
    }
};

扩展:

康托公式的另一种用法~~~~:上面的那个反向思维一下

第二类题:已知是n = 5,求14352是它的第几个序列?(同一道题)

用刚才的那道题的反向思维:

第一位是1,有0个数小于1,即0* 4!

第二位是4,有2个数小于4,即2* 3!

第三位是3,有1个数小于3,即1* 2!

第四位是5,有1个数小于5,即1* 1!

第五位是2,不过不用算,因为肯定是0

所以14352是 n = 5的第 0 + 12 + 2 + 1 + 0 = 15 + 1(求的是第几个,所以要加一) = 16

第16个,跟刚才那道题一样,证明对了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值