Permutation Sequence

来源:互联网 发布:c语言移位操作 编辑:程序博客网 时间:2024/06/11 04:26

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.


首先采用DFS方法来做,但是太慢,k=9时就超时。

然后仔细分析规律,可以发现:

设变量K1 = K
a1 = K1 / (n-1)!// 最左位

同理,a2的值可以推导为

K2 = K1 % (n-1)!
a2 = K2 / (n-2)!


...

K(n-1) = K(n-2) /2!
a(n-1) = K(n-1) / 1!

an = K(n-1)

具体实现的过程中需要一个数组来保存剩余可以用的数字(因为不能重复),用作当前位后需要删除该数字。

每次循环找到没使用过的数中第k/data[i]个数就是当前位的数字,data[i]保存(n-1)!的值。

注意:因为下标从0开始,需要k--

string getPermutation(int n, int k){    int data[n+1];    data[0]=1;    int num[n];    for(int i=1; i<=n; i++)    {        data[i]=data[i-1]*i;        num[i-1]=i;    }    string result;    k--;    for(int i=n-1; i>=0; i--)    {        int div=k/data[i];        result += (char)(num[div] + '0');        for(int j = div; j < n; j++)            num[j] = num[j+1];        k=k%data[i];    }    return result;}

=================== DFS 超时方法 ================================

vector<bool> used;string res;int temp[10];void Permute(int &n, int depth, int &k){    if(depth==n)    {        k--;        if(k==0)        {            for(int i=0; i<n; i++)               res += (char)(temp[i] + '0');        }    }    else        for(int i=1; i<=n; i++)        {            if(used[i]==false)            {                used[i]=true;                temp[depth]=i;                Permute(n,depth+1,k);                used[i]=false;            }        }}string getPermutation(int n, int k){    for(int i=0; i<=n; i++)        used.push_back(false);    Permute(n,0,k);    return res;}





0 0