Permutation Sequence

来源:互联网 发布:log4j 写入mysql 编辑:程序博客网 时间:2024/05/18 12:37

Permutation Sequence

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个元素,第k个permutation是a1, a2, ... ,an,可以先确定第一个元素a1,之后的元素采用相同的方法逐一确定。具体如下:

去掉a1后, a2, a3, .... .... an, 共计n-1个元素, 这n-1个元素共有(n-1)!种排列

a1的值可以推导为

k1 = k

ax1 = k1 / (n-1)! 

a2的值可以推导为

k2 = k1 % (n-1)!

ax2 = k2 / (n-2)!

以此类推。

注意:ax1并不是表示a1,a1的确定:先建立一个标记数组flag,其中,flag[i]=0表示元素i还没使用,第ax1个零标记的元素就是a1

代码:

int flag[10];void perm(string &s, int n, int k){    long long jc[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};    bool ed = true;    int x, y;    if(n == 0) return;    x = k / jc[n - 1];    y = k % jc[n - 1];    //cout<<k<<' '<<jc[n-1]<<' '<< x <<' '<<y<<endl;    for(int i = 1; i <= 9; i ++)    {        if(flag[i]==0) x --;        if(x == -1)        {            flag[i] = 1;            char a = i + '0';            s = s + a;            break;        }    }    perm(s, n - 1, y);}string getPermutation(int n, int k){    string s = "";    memset(flag, sizeof(flag), 0);    perm(s, n, k - 1);    return s;}


0 0
原创粉丝点击