题目描述:
The set [1,2,3,…,n]
contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
分析:
题意:正整型数集合 [1,2,3,…,n]
包含 n! 种不同的排列。给定 n (1→9) 和 k,返回第k个字典序排列。
对于i∈{3,2,1},重复以上步骤,获得ans = "213"。
时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
// Note: Given n will be between 1 and 9 inclusive.
class Solution {
public:
string getPermutation(int n, int k) {
// Exceptional Case:
if(n == 1){
return "1";
}
string str = "";
// get n!
int N = 1;
for(int i = 2; i <= n; i++){
N *= i;
}
// get "1234...n"
for(int i = 1; i <= n; i++){
str += (i + '0');
}
string ans = "";
// check if k > N
int kk = (k - 1) % N + 1;
for(int i = n; i >= 1; i--){
N /= i;
int cnt = (kk - 1) / N;
ans += str[cnt];
kk -= cnt * N;
str.erase(cnt, 1);
}
return ans;
}
};