60. Permutation Sequence

来源:互联网 发布:手机域名是什么 编辑:程序博客网 时间:2024/06/05 19:43

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.



class Solution {public:    string getPermutation(int n, int k) {        int total = factorial(n);        string candidate = string("123456789").substr(0,n);        string res(n,' ');                for(int i = 0; i < n; i++){            total /= (n-i);            int tmp = (k-1)/total;            res[i] = candidate[tmp];            candidate.erase(tmp,1);            k-=total*tmp;        }        return res;    }        int factorial(int n){        int res = 1;        for(int i = 2; i <= n; i++){            res*=i;        }        return res;    }};

求第k个排列,通过C++里面的next_permutation()函数求解,超时,然后通过筛选的方式求解,通过逐个确定每个位置的数字,首先通过通过(k-1)/(n-1)!固定某个数。通过m=(k-1)/(n-1)!,该数就是原数组的第m个数,第一个数固定后,我们从candidate数组中删除该数,那么就相当于在当前src的基础上求第k - m*(n-1)!个排列。通过n次逐个确定每个位置的值。

0 0
原创粉丝点击