[LeetCode] 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):

“123”
“132”
“213”
“231”
“312”
“321”

Given n and k, return the k th permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

解题思路:
直接全排列暴力破解,会超时也可能会超内存;

第一个数一定是123…n,所以第一位以1开头的数有(n-1)!种可能,
所以第二位以某个数开头有(n-2)!中可能
同理…
所以我们求每一位上的值是多少?
第一位是多少呢?
k/(n-1)!
第二位是多少呢?
k=k%(n-1)!
k/(n-2)!
同理一直算到最后一位数。

    string getPermutation(int n, int k) {
        k--;//题意从1开始
        string ans;
        if(n <= 0){
            return ans;
        }
        int cnt = 1;
        int *kk = new int[n];
        for(int i = 0; i< n; i++){
            kk[i] = i+1;
            cnt *= (i+1);
        }
        for(int i =0 ; i< n; i++){
            cnt /= (n - i);
            int index = k/cnt;
            ans += char(kk[index] + '0');
            for(int j = index; j < n - i - 1 ; j++){
                kk[j] = kk[j +1];
            }
            k %= cnt;
        }
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/u014253011/article/details/82430594