leetcode:Permutation Sequence
2016-03-13 20:39
281 查看
The set
unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
Subscribe to see which companies asked this question
[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.
Subscribe to see which companies asked this question
class Solution { private: unsigned int hashTable[9]; unsigned int getPai(int n) { if (n == 0) return 1; if (hashTable != 0) return hashTable ; if (n==1) { hashTable[1] = 1; return 1; } unsigned int ret = n*getPai(n-1); hashTable = ret; return ret; } string getPermutationHelper(vector<char> &model, int k) { int n = model.size(); if (n == 0) return ""; int numIdx = (k-1) / getPai(n-1); // (k-1) 这里很关键 int remain = k - numIdx*getPai(n-1); // remain = k-numIdx*getPai(n-1)也很关键 char targetChar = model[numIdx]; vector<char> next; for (int i=0; i<model.size(); i++) { if (i != numIdx) next.push_back(model[i]); } return model[numIdx] + getPermutationHelper(next, remain); } public: string getPermutation(int n, int k) { vector<char> model(n); for (int i=1; i<=n; i++) { model[i-1] = i+'0'; } return getPermutationHelper(model, k); } };
相关文章推荐
- codeforces 3D . Least Cost Bracket Sequence 贪心
- CodeForces 622A--F - Infinite Sequence
- 用UIToolBar实现简单毛玻璃效果
- POJ1947 Rebuilding Roads(树形DP)
- stl之适配器容器——stack, queue, priority_queue
- stl之序列容器——deque
- 利用UIImageJPEGRepresentation与UIGraphicsBeginImageContext进行图片压缩的简单比较
- 优先队列(Priority Queue)
- LeetCode 之 Unique Paths
- 63. Unique Paths II
- Android spannableStringBuilder用法整理
- UVA1152 4 Values whose Sum is 0
- GUI布局
- Penguins DbTools数据库管理移植差分工具(EXCEL相关) ver 20160313
- android studio 报Error:failed to find Build Tools revision XXXX
- php使用mysql_query查询超大结果集超内存的解决方法
- leetcode:Repeated DNA Sequences
- PowerBuilder创建和链接数据库
- String,StringBuffer与StringBuilder的区别及应用场景
- SQLServer中有五种约束,Primary Key约束、Foreign Key约束、Unique约束、Default约束和Check约束,今天使用SQL Server2008来演示下这几种约束的