Permutation Sequence

来源:互联网 发布:锐思数据库 编辑:程序博客网 时间:2024/05/01 17:11

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.

就是给你一个数字范围,让你求第k个排列

一开始想的是直接上来递归模拟,没想太多,只不过,阶乘这个东西的增长速度实在太快了,我都没有料到9的阶乘竟然可以达到362880.。。。在这里也当个教训

看到Note就大致知道了该怎么去模拟这道题

思路:

如果n=4,k=5

5<3!

所以第一个数字肯定是1,把1从vector里删除

继续5>2! 所以k = 5-2 = 3

3>2! k = 3-2 = 1

减了2次,所以第二个数字应该选vector里面的下标为2的元素,即4

第三个

1=1!  ,所以第三个数字直接选vector里面下标为0的元素,即2

第四个数字时,vector里面只剩下一个元素,所以第四个为3

即1 4 2 3

class Solution {public:    int num[8] = {1,2,6,24,120,720,5040,40320};    string getPermutation(int n, int k) {        vector<int> v;        for(int i=0;i<n;i++)            v.push_back(i+1);        string shit = "";        int cur = 0;        while(k>0){            int idx = 0;            if(n-2-cur<0){                k--;            }else{                while(k>num[n-2-cur]){                    k-=num[n-2-cur];                    idx++;                }            }            char c = v[idx]+'0';            vector<int>::iterator it = v.begin()+idx;            v.erase(it);            shit+=c;            cur++;        }        return shit;    }};

直接打表出到8的阶乘

ac

0 0
原创粉丝点击