Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
permutation-sequence.cpp 1.05 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: O(n^2)
// Space: O(n)
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> nums;
int total = 1;
for (int i = 1; i <= n; ++i) {
nums.emplace_back(i);
total *= i;
}
// Cantor Ordering:
// Construct the k-th permutation with a list of n numbers
// Idea: group all permutations according to their first number (so n groups, each of
// (n - 1)! numbers), find the group where the k-th permutation belongs, remove the common
// first number from the list and append it to the resulting string, and iteratively
// construct the (((k - 1) % (n - 1)!) + 1)-th permutation with the remaining n-1 numbers
int group = total;
stringstream permutation;
while (n > 0) {
group /= n;
int idx = (k - 1) / group;
permutation << nums[idx];
nums.erase(nums.begin() + idx);
k = (k - 1) % group + 1;
--n;
}
return permutation.str();
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助