Permutation Sequence
Mar 28 '12
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.
解法:算法见http://blog.youkuaiyun.com/zephyr_be_brave/article/details/9730967.实现时候注意用arr和index两个数组的实现方法。
class Solution {
public:
string getPermutation(int n, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n == 0) return "";
if(n == 1) return "1";
k -= 1;
vector<int> index(n,0);
int factor = 1;
for(int i = 1;i < n;i++)
{
factor *= i;
index[i] = factor;
}
for(int i = index.size()-1;i > 0;i--)
{
int temp = k/index[i];
k -= temp * index[i];
index[i] = temp;
}
string res;
vector<int> arr;
for(int i = 0; i< n;i++) arr.push_back(i+1);
for(int i = index.size()-1;i >= 0;i--)
{
res.append(1,'0'+ arr[index[i]]);
arr.erase(arr.begin()+index[i]);
}
return res;
}
};
20 milli secs.