首页 > 代码库 > LeetCode "Permutation Sequence"
LeetCode "Permutation Sequence"
1A! This is actually a basic question in Combinatorics: if at digit[k] = n, it contributes (k-1)! * n to the targeted index.
class Solution {public: unsigned long long nPrime(unsigned n) { if (n == 1) return 1; return n * nPrime(n - 1); } string getPermutation(int n, int k) { if (n == 1) return "1"; unsigned long long nbase = nPrime(n - 1); k--; // Record counts vector<int> inx; for (int i = n; i >= 1; i--) { int currInx = k / nbase; inx.push_back(currInx); k -= nbase * currInx; if(nbase > 1) nbase /= (i - 1); } // Recover digits string ret; unordered_set<int> mark; for (int i = 0; i < inx.size(); i++) { int currInx = inx[i]; int k; for (k = 0; k < 9 && currInx >= 0; k ++) { if (mark.find(k) == mark.end()) currInx--; } ret += ‘0‘ + k; mark.insert(k - 1); } return ret; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。