Permutation Sequence
The set[1,2,3,…,n]
contains a
total ofn! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, forn= 3):
"123"
"132"
"213"
"231"
"312"
"321"
Givennandk, return thekthpermutation sequence.
Note:Givennwill be between 1 and 9 inclusive.
本题最直接的算法就是,一个一个permutation的产生,然后数到k就是答案了,但是这样的程序很慢,高手是不能这样写程序的。O(∩_∩)O~
其实这类题有个很特别的方法做的,不过没看过的话,就很难想出来了。
可以参考下面博客,求一个数列的全部全排列。而不同的就是这里只是求某个特定的全排列。
http://blog.csdn.net/kenden23/article/details/17166105
使用上面博客中的最后一个方法,定位下标的方法就可以写出很快的程序了。
下面程序8ms都可以过,我分了几个函数,希望可以清晰一点吧。
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> bound = generatBound(n);
vector<int> table = converNumToTable(bound, n, k);
return permuteK(n, k, bound, table);
}
string permuteK(int n, int k, vector<int> &bound, vector<int> &table)
{
vector<int> num(n);
string res;
for (int i = 1; i <= n; i++)
{
num[i-1] = i;
}
for (int j = 0; j < n; j++)
{
res.push_back(num[table[j]] + '0');
num.erase(num.begin()+table[j]);
}
return res;
}
vector<int> converNumToTable(vector<int> &bound, int n, int num)
{
vector<int> table(n);
num--;
for (int i = n-2; i>=0 && num > 0; i--)
{
table[i] = num % (bound[i]+1);
num /= (bound[i]+1);
}
return table;
}
vector<int> generatBound(int n)
{
vector<int> bound(n);
for (int i = 0; i < n; i++)
{
bound[i] = n-1-i;
}
return bound;
}
};
//2014-1-29 update
vector<int> table;
string getPermutation(int n, int k)
{
convertToTable(n, k-1);
string s, rs;
for (int i = 1; i <= n; i++)
{
s.push_back(i+'0');
}
for (int i = 0; i < n; i++)
{
rs.push_back(s[table[i]]);
s.erase(s.begin()+table[i]);
}
return rs;
}
void convertToTable(int n, int k)
{
table.clear();
table.resize(n);
for (int i = n - 2, j = 2; i >= 0 && k > 0; i--, j++)
{
table[i] = k%j;
k /= j;
}
}
分享到:
相关推荐
Source file for LeetCode Permutations Problem
刷LeetCode刷LeetCode刷LeetCode刷LeetCode刷LeetCode
大佬的leetcode刷题笔记(c++版本)
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101.zip
vs code LeetCode 插件
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101_源码.zip
leetcode中文版
100个leetCode详细解答
terminal-leetcode, 终端Leetcode是基于终端的Leetcode网站查看器 终端 leetcode终端leetcode是基于终端的leetcode网站查看器。本项目是由 RTV 激发的。 我最近正在学习本地化的反应,以实践我的新知识,并根据这个...
LeetCode 刷题汇总1
LeetCode 选讲1
leetcode刷题, 直接用leetcode的分类方式.
该分类为结合《算法导论》的内容,给出Leetcode题目分类。题目主要集中在Leetcode的前400题中,也包括有后面的一些经典值得刷的题。该题目分类按照算法和数据结构排版,即可供单独Leetcode刷题使用,也可以配合学习...
这份文档列出了leetcode几乎所有题目(大约134题)的分类以及难度指示,是刷leetcode的必备良品。现在leetcode总的题目数已经达到150题,所以有部分题目没有包含在这个文档中,但是——足够了。po主刷leetcode的时候...
leetcode高频面试笔试题150+道,亲身总结。
LeetCode 刷题笔记
(C++)LeetCode刷题题解答案
LeetCode面试笔试题
LeetCode 刷题
leetcode全套解答python版本。包括更新到10月份的的leetcode