【LeetCode】60. 第k個排列
阿新 • • 發佈:2018-11-07
題目連結:https://leetcode-cn.com/problems/permutation-sequence/description/
題目描述
給出集合 [1,2,3,…,n],其所有元素共有 n! 種排列。
按大小順序列出所有排列情況,並一一標記,當 n = 3 時, 所有排列如下:
“123”
“132”
“213”
“231”
“312”
“321”
給定 n 和 k,返回第 k 個排列。
說明:
- 給定 n 的範圍是 [1, 9]。
- 給定 k 的範圍是[1, n!]。
示例
輸入: n = 3, k = 3
輸出: “213”
輸入: n = 4, k = 9
輸出: “2314”
解決方法
解題思路:使用庫函式next_permutation
class Solution {
public:
string getPermutation(int n, int k) {
string str;
for (int i=1;i<=n;i++)
str+=(char)(i+'0');
int i=1;
do
{
if (i==k) return str;
i++ ;
}while(next_permutation(str.begin(),str.end()));
}
};