Leetcode 60 Permutation Sequence
题目原文
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.
题意分析
寻找按字典排序的第k个序列。
解法分析
对于一个n,可以构建n的所有排列的排列树,树的叶子数代表总的排列数,共n!个,对于第一层的n个子树,每个子树包含(n-1)!个序列,通过k与(n-1)!的取商取余,可以逐步寻找到相应解,c++代码如下:
class Solution {
private:
int N;//total path in each layer
int curPath;
int K;//the order in each layer
public:
int pathNumber(int layer) {
int i;
curPath = 1;
for (i = 1; i <= (N - layer); i++) {
curPath = curPath*i;
}
int temp = K / (curPath / (N - layer));
if (K % (curPath / (N - layer)) == 0) {
K = curPath / (N - layer);
return temp - 1;
}
else {
K = K % (curPath / (N - layer));
return temp;
}
}
string getPermutation(int n, int k) {
N = n;
K = k ;
string res;
vector<int> num;
int i;
for (i = 1; i <= n; i++) {
num.push_back(i);
}
if (n == 1)
return "1";
int whichWay;
for (i = 0; i<n; i++) {
whichWay = pathNumber(i);
res.push_back('0'+num[whichWay]);
num.erase(num.begin() + whichWay);
}
//res.push_back(num[0]);
return res;
}
};