Permutation Sequence

来源:互联网 发布:lol请检查网络连接 编辑:程序博客网 时间:2024/06/05 19:35

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.

给定所有排列集合按升序排列,公用n!=n*(n-1)个。那么第一个数字为 k/(n-1)! 剩下的为k%(n-1)! 一直到最后一位。 

code第九行用的是k-1, 我认为是归纳的结果,网上的说为了迎合0-n-1的说法,我没明白。 我们在计算第一位 去集合 k=[1,2,3,4,5,6] 对应第一位集合 为 [0, 0, 1, 1, 2, 2]。 如果不用k-1,那就是 [0, 1, 1, 2, 2, 3], 所以k-1刚好凑出来。。。。反正我是没想明白别的解释。。。

class Solution {public:    string getPermutation(int n, int k) {    string candidate=string("123456789").substr(0,n);    string res(n,'0');    int fac=factor(n);    for (int i=0; i<n; i++){    fac/=n-i; /* (n-1)! */    int index=(k-1)/fac; /*indexing the k to adapt with 0-n-1*/    res[i]=candidate[index];    candidate.erase(index,1);    k-=index*fac;    }    return res;    }    /* calculate n!*/    int factor(int n)    {        int mult=1;        for(int i=2; i<=n; i++)        mult*=i;        return mult;    }};




0 0