题目要求如下:
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,定义一个map存储 1到 n这n个值。C++ 的STL map是根据key大小排序的
2,要高清排序规则,就拿题干中的例子举例:
比如第三位213,如果从零开始排位,它就是k = k - 1 =2;
2.1 k / (n-1)! = 2 / 2 = 1, map里面有三个key 1,2,3选择序号是1的即2,然后删除此值, k = k % (n-1)! = 0
2.2 0 / (n-2)! = 0 / 1 = 0, map里面有两个key 1,3选择序号是0的即1,然后删除此值,k = k % (n-2)! = 0
2.3 只剩一个值,就是3.
213为最终解,
代码如下:
class Solution {
public:
string getPermutation(int n, int k) {
string retVal = "";
map<int, int> num_map;
map<int, int>::iterator it;
for (int i = 1; i <= n; ++i)
num_map[i] = i;
int tmp_n = n - 1;
k = k - 1;
while (tmp_n >= 0) {
int tmp = k / factorial(tmp_n);
k = k % factorial(tmp_n);
for (it = num_map.begin(); it != num_map.end(); ++it) {
if (tmp == 0){
retVal += to_string(it->first);
num_map.erase(it);
break;
}
else
--tmp;
}
--tmp_n;
}
return retVal;
}
private:
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i)
result *= i;
return result;
}
};