Leetcode 60. Permutation Sequence

来源:互联网 发布:mac怎么上传淘宝助理 编辑:程序博客网 时间:2024/06/05 05:18

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.

s思路:
1. 把所有1-9的排列数预先计算出来,即:{0,1,2,6,24,120,720,5040,40320,362880}。例如:n=4时:

1,2,3,41,2,4,31,3,2,41,3,4,21,4,2,31,4,3,22,1,3,42,1,4,32,3,1,42,3,4,12,4,1,32,4,3,13,1,2,43,1,4,2...

s上面列举了前14个排列。可以看出规律,第一位为1的有6个,为2、3、4的都有6个,为什么是6?因为第三个数的排列数刚好是6。所以,先用k/6得到第一位的数,然后k=k%6,在用k/2得到第二位数,然后更新k=k%2;最后k/1得到第三位数,剩下的数就是第四位数

class Solution {public:    string getPermutation(int n, int k) {        //        //vector<int> fact{0,1,2,6,24,120,720,5040,40320,362880};        int fact[10]={0,1,2,6,24,120,720,5040,40320,362880};//优化:用array比vector速度快!!        //这样不好set<int> ss{0,1,2,3,4,5,6,7,8,9};//        string num="123456789";//简洁的存储数据,不用搞成set<int>,再取出数to_string(),就太不简洁        string res="";        k--;        n--;        while(n>0){            int idx=k/fact[n];            res+=num[idx];            k=k%fact[n];            num.erase(idx,1);//idx开头长度为1            n--;        }        res+=num[0];        return res;    }};
0 0
原创粉丝点击