LeetCode—60. Permutation Sequence

Type:medium

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 for?n?= 3:

"123"

"132"

"213"

"231"

"312"

"321"

Given?n?and?k, return the?kth?permutation sequence.

Note:

Given?n?will be between 1 and 9 inclusive.

Givenkwill be between 1 and?n! inclusive.

Example 1:

Input:n = 3, k = 3Output:"213"


本題要求求出n個(gè)數(shù)字排列組合的第k個(gè)數(shù),根據(jù)例子中我們可以看出來,當(dāng)給定n時(shí),選好第一個(gè)數(shù)字,可以將(n-1)!個(gè)數(shù)值當(dāng)作一組,(因?yàn)樗麄兊牡谝粋€(gè)數(shù)字相同),當(dāng)選好第一個(gè)數(shù)字和第二個(gè)數(shù)字后,(n-2)!個(gè)數(shù)值可以當(dāng)作一組(因?yàn)樗麄兊牡谝弧⒍€(gè)數(shù)字相同)。那么給定k時(shí),第一次可以用k除以(n-1)!的商來判斷結(jié)果的第一個(gè)數(shù)字,而k除以(n-1)!的余數(shù)則是它在分組后的小組中排列的位置。以此類推。



class Solution {

public:

? ? string getPermutation(int n, int k) {

? ? ? ? string res;

? ? ? ? string num = "123456789";

? ? ? ? vector<int> f(n, 1);

? ? ? ? //f[i]記錄i!的值

? ? ? ? for (int i = 1; i < n; ++i) f[i] = f[i - 1] * i;

? ? ? ? --k;

? ? ? ? for (int i = n; i >= 1; --i) {

? ? ? ? ? ? int j = k / f[i - 1];

? ? ? ? ? ? k %= f[i - 1];

? ? ? ? ? ? res.push_back(num[j]);

? ? ? ? ? ? num.erase(j, 1);

? ? ? ? }

? ? ? ? return res;

? ? }

};

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容