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.

思路:这道题的意思是顺序找出1~n的第k个排列组合,并返回。大家可以搜索一下“康托展开”就知道该如何做了。考虑一下,给你n-1个数组成排列,最多有(n-1)!种情况,当第n个数(这个数可以是1~n中的一个数),每增加1,排列情况就会增加(n-1)!种。所以,k/(n-1)!可以得到最高位(从左往右)应该出现的数字,在计算后面的位数,进入下一循环的条件k=k%(n-1)!;如果是第i位的时候,应该在剩下的数字中找出第k/(i-1)!个。为了表示已经访问过的数字,我们使用visited来记录。data记录0~n位的阶乘结果。

class Solution {

public:

    string getPermutation(int n, int k) {

        int data[10];

        vector<bool> visited(10,0);

        data[0]=1;

        for(int i=1;i<=n;i++)

        {

            data[i]=data[i-1]*i;

        }

        string str(n,'0');

        --k;            //从0位开始算起

        for(int i=n-1;i>=0;i--)

        {

            int temp_k=k/data[i];

            int j=1;

            for(;j<10;j++)

            {

                if(visited[j]==0)

                    temp_k--;

                if(temp_k<0)

                    break;

            }

            visited[j]=1;

            str[n-i-1]='0'+j;

            k=k%data[i];

        }

        return str;

    }

};

 

你可能感兴趣的:(sequence)