leetcode60 - Permutation Sequence - hard
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.
- Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3 Output: "213"
Example 2:
Input: n = 4, k = 9 Output: "2314"
看了最优解做的。大致是把所有的permutations break town来思考。比如说如果我们确定了最高位,那可以分成三组(分别是首位为1or2or3),每组2个。接下来每组中如果确定第二位,可以分成两组,每组1个,以此类推,这样就每次缩小了寻找范围。
首先,确定第i (0~n-1)位后,当前这个大group就可以被拆分成每组有npg=factorial(n-1-i)个数的小groups。那kth就落在第k/npg个组,接下来我们就在这个组里找第k%npg个数。确认一个数字的位置后,要把标成不可再用。
细节:
int to char: '0'+c;
加进string里 res[i]=x不行,用res+=x
实现:Time O(n^2) Space O(n)
class Solution { public: string getPermutation(int n, int k) { vector<int> factorial(n); factorial[0] = 1; for (int i=1; i<n; i++){ factorial[i] = factorial[i-1]*i; } vector<int> available; for (int i=1; i<=n; i++){ available.push_back(i); } k-=1; string res = ""; for (int i=0; i<n; i++){ int numPerGroup = factorial[n-1-i]; int group = k/numPerGroup; int cur = available[group]; res += '0'+ cur; available.erase(find(available.begin(), available.end(), cur)); k %= numPerGroup; } return res; } };

浙公网安备 33010602011771号