给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
“123” “132” “213” “231” “312” “321”
给定 n 和 k,返回第 k 个排列。
说明:
给定 n 的范围是 [1, 9]。
给定 k 的范围是[1, n!]。
示例 1:
输入: n = 3, k = 3
输出: "213"
示例 2:
输入: n = 4, k = 9
输出: "2314"
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/permutation-sequence 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
string getPermutation(int n, int k) {
string ans, temp;
bool visited[10] = {0};
int count = 0;
permute(n, k, count, 0, temp, ans, visited);
return ans;
}
void permute(int &n, int &k, int& count, int bit, string &temp, string &ans, bool* visited)
{
if(count > k)
return;
if(bit == n)
{
count++;
if(count == k)
ans = temp;
}
for(int i = 1; i <= n; i++)
{
if(visited[i])// i写入了答案,继续下一个数
continue;
temp.push_back(i+'0');
visited[i]=true;
permute(n, k, count, bit+1, temp, ans, visited);
temp.pop_back();
visited[i]=false;
}
}
};
class Solution {
public:
string getPermutation(int n, int k) {
int factor[10] = {1,1,2,6,24,120,720,5040,40320,362880};//阶乘数
string num = "123456789";
string ans;
int bit;
while(n > 0)
{
bit = (k-1)/factor[n-1];//确定第一位数的时候,后面有f[n-1]种排列
ans.push_back(num[bit]);
num.erase(num.begin()+bit);//该位数写入答案了,删除
k -= bit*factor[n-1];
n--;
}
return ans;
}
};