题目:
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.
解答:这道题让人想到可以使用Leetcode中 Next Permutation的方法,并使用该方法迭代k - 1次,则得到结果。但是OJ的结果是Time Limit Exceeded.
代码:
class Solution {
string nextPermutation(string str) {
if(str.length() < 2)
return str;
int i = -1, j;
for(i = str.length() - 2; i >= 0; i--)
{
if(str[i] < str[i + 1])
break;
}
if(i > -1)
{
for(j = str.length() - 1; j > i; j--)
{
if(str[j] > str[i])
break;
}
char t = str[i];
str[i] = str[j];
str[j] = t;
}
i++;
for(int j = 0; j < (str.length() - i) / 2; j++)
{
char t = str[i + j];
str[i + j] = str[str.length() - j - 1];
str[str.length() - j - 1] = t;
}
return str;
}
public:
string getPermutation(int n, int k) {
string str;
for(int i = 1; i < n + 1; i++)
str.append(1, i + '0');
for(int i = 0; i < k - 1; i++)
str = nextPermutation(str);
return str;
}
};
思路二:
从例子中寻找一个规律,假设numbers = {1, 2, 3}, 那么在全排列序列中,第一个元素是(k - 1 )/ (n - 1)! + 1, 在numbers中下标是(k - 1 )/ (n - 1)! . 将该元素从Numbers中取出,append到结果字符串,并且将numbers中该元素从numbers中删除。这个规律可以类推下去,在numbers中剩余元素中依次选择出结果字符串中下标为1,....,n - 1的元素。
代码:
class Solution {
public:
string getPermutation(int n, int k) {
// create a factorial map
string ret;
vector<int> numbers(n);
int product = 1;
for(int i = 0; i < n; i++)
{
numbers[i] = i + 1;
product *= (i + 1);
}
k = k - 1;
product /= n;
for(int i = 0; i < n - 1; i++)
{
int select = (k / product);
ret.append(1, '0' + numbers[select]);
numbers.erase(numbers.begin() + select);
k = k % product;
product /= (n - i - 1);
}
ret.append(1, '0' + numbers[0]);
return ret;
}
};