# [60. Permutation Sequence (Hard)](https://leetcode.com/problems/permutation-sequence/)
<p>The set <code>[1, 2, 3, ..., n]</code> contains a total of <code>n!</code> unique permutations.</p>
<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>
<ol>
<li><code>"123"</code></li>
<li><code>"132"</code></li>
<li><code>"213"</code></li>
<li><code>"231"</code></li>
<li><code>"312"</code></li>
<li><code>"321"</code></li>
</ol>
<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre><p><strong>Example 2:</strong></p>
<pre><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"
</pre><p><strong>Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> "123"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 9</code></li>
<li><code>1 <= k <= n!</code></li>
</ul>
**Related Topics**:
[Math](https://leetcode.com/tag/math/), [Backtracking](https://leetcode.com/tag/backtracking/)
**Similar Questions**:
* [Next Permutation (Medium)](https://leetcode.com/problems/next-permutation/)
* [Permutations (Medium)](https://leetcode.com/problems/permutations/)
## Solution 1. Brute Force
```cpp
// OJ: https://leetcode.com/problems/permutation-sequence/
// Author: github.com/lzl124631x
// Time: O(NK)
// Space: O(1)
class Solution {
public:
string getPermutation(int n, int k) {
string ans;
for (int i = 0; i < n; ++i) ans += ('1' + i);
while (--k) next_permutation(begin(ans), end(ans));
return ans;
}
};
```
## Solution 2.
```cpp
// OJ: https://leetcode.com/problems/permutation-sequence/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(1)
class Solution {
public:
string getPermutation(int n, int k) {
int fact = 1;
string ans;
for (int i = 1; i <= n; ++i) {
fact *= i;
ans += '0' + i;
}
--k;
for (int i = 0; i < n; ++i) {
fact /= n - i;
int j = k / fact + i, tmp = ans[j];
for (; j > i; --j) ans[j] = ans[j - 1];
ans[j] = tmp;
k %= fact;
}
return ans;
}
};
```
c++-c++编程基础之leetcode题解第60题排列序列.zip
需积分: 1 121 浏览量
2024-04-09
04:49:18
上传
评论
收藏 2KB ZIP 举报
__AtYou__
- 粉丝: 1214
- 资源: 267
最新资源
- sony 索尼IMX334摄像头模组电路板AD版硬件PCB图(6层板).zip
- 基于flask和echarts融合交易策略的bitfinex可视化微服务.zip
- 包含了wvp-assist.tar wvp-talk.tar zlmediakit.tar .
- 3r4efgh53wgrf43tw
- 2024新版Java基础从入门到精通全套视频+资料下载
- Spring AI大模型视频教程+ChatGPT视频教程+OpenAI大模型视频教程(资料+视频教程)
- ABB工业机器人教程PDF版本
- 123321123323211
- yolov8实战第八天-pyqt5-yolov8实现车牌识别系统(论文(8700+字+数据集+完整部署代码+代码使用说明)
- 三相桥式全桥整流电路MATALB Simulink仿真文件
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈