Permutation Sequence (LeetCode)
Question:
https://leetcode.com/problems/permutation-sequence/
N个字符的permutation个数是N!,所以对于N个字符的数列,如果最开始的字符是第kth大的 (starting from 1),则它可能的取值范围是 ((k-1)*((N-1)!) + 1) 到 (k*((N-1)!)。
所以对于N数列,当前值在数列中的index值(k)可以如下计算可得:
k = number / ((N-1)!)
class Solution { public: string getPermutation(int n, int k) { vector<int> table(n, 0); BuildTable(table, n); vector<char> restChars; for (int i = 1; i <= n; i++) { restChars.push_back(i+'0'); } string result; k = k-1; // starting from 0 for (int i = 0; i < n-1; i++) { // k must < table[i] int indexToRemove = k/table[i+1]; result.push_back(restChars[indexToRemove]); restChars.erase(restChars.begin()+indexToRemove); k = k%table[i+1]; } result.push_back(restChars[0]); return result; } void BuildTable(vector<int>& table, int n) { table[n-1] = 1; int i = 2; int index = n-2; while (i <= n) { table[index] = table[index+1] * i; i++; index--; } } };
浙公网安备 33010602011771号