LeetCode Permutation Sequence
class Solution { public: string getPermutation(int n, int k) { k--; if (n < 1 || k < 0) return ""; vector<int> nums(n, 0); long seg = 1; for (int i=0; i<n; i++) { nums[i] = i + 1; seg = seg * (nums[i]); } if (k >= seg) return ""; int idx = 0; for (int i=0; i < n-1; i++) { seg = seg / (n - i); idx = k / seg + i; k = k % seg; int sel = nums[idx]; for (int j = idx; j>i; j--) { nums[j] = nums[j - 1]; } nums[i] = sel; } string res; for (int i=0; i<n; i++) { res.push_back((char)(nums[i] + '0')); } return res; } };
复杂度O(n^2), 但是因为参数k用int表示了,说明n的值不会太大,否则n!(k最大值)轻轻松松超过int范围
第二轮:
class Solution { public: string getPermutation(int n, int k) { int mag[10] = {1}; for (int i=1; i<n; i++) { mag[i] = mag[i-1] * i; } string res; int idx = n - 1; int ds[] = {1,2,3,4,5,6,7,8,9}; k--; while (idx >= 0) { int d = k / mag[idx]; k = k % mag[idx]; for (int i=0; i<9; i++) { if (d == 0 && ds[i] != 0) { d = ds[i]; ds[i] = 0; break; } if (ds[i] != 0) { d--; } } res.push_back('0' + d); idx--; } return res; } };