您的位置:首页 > 产品设计 > UI/UE

[Leetcode] 60. Permutation Sequence 解题报告

2017-01-15 04:08 337 查看
题目

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.
思路[/b]:

1、nextPermutation法:由于我们之前已经实现了nextPermutation,所以只需要先生成一个最小的permutation,然后连续调用k-1次nextPermutation,就可以得到所需要的结果。由于调用nextPermutation的时间复杂度是O(n),所以该思路的时间复杂度是O(n*k),空间复杂度可以做到O(1)(可以直接在string上面做nextPermutation)。此算法仅仅在k <= n的情况下有优势。

2、迭代法:长度为n的字符串的permutation的个数为O(n!),而以任何一个字符开头的permutation共有O((n-1)!)个。通过k值,我们可以首先确定结果字符串中第一个字符;然后更新k值,并且在剩下的字符集合中采取相同的策略确定下一个字符。重复该过程直到n个字符全部被确定。在实现中如果采用vector来表示剩余字符集,则由于每次删除字符集中第k大的字符的时间复杂度高达O(n),所以整个算法的时间复杂度为O(n^2),空间复杂度为O(n)。由于通常情况下 k >> n,所以平均而言思路2比思路1更有优势。(如果有一种数据结构能在最多O(logn)的时间复杂度内完成查找和删除第i大的元素,则该算法的时间复杂度可以进一步降低为O(nlogn),有木有这样的数据结构?)

代码

class Solution {
public:
string getPermutation(int n, int k)
{
string ret;
long long factorial = 1;                // the indices
vector<char> nums(n, '0');              // the letter set
for(int i = 0; i < n; ++i)
{
factorial *= (i == 0 ? 1 : i);
nums[i] = '0' + (i + 1);
}
k--;                                    // convert to 0-based index
for(int i = n - 1; i >= 0; --i)
{
int j = k / factorial;              // determine the next letter to be added
ret.push_back(nums[j]);
nums.erase(nums.begin()+j);
k %= factorial;                     // update the index
if(i > 0)
factorial /= i;
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: