LeetCode-Permutation Sequence
2013-10-07 21:32
507 查看
The set
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.
预先把1-9的阶乘都算出来,剩下就可以简单粗暴了
View Code
[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.
预先把1-9的阶乘都算出来,剩下就可以简单粗暴了
class Solution { public: string getPermutation(int n, int k) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> per; if(n==0) return""; if(n==1) return"1"; per.resize(9); per[0]=1; k--; for(int i=1;i<9;i++){ per[i]=per[i-1]*(i+1); } k=k%per[n-1]; vector<int> vvv; vvv.resize(9); string ret=""; for(int i=0;i<9;i++)vvv[i]=i+1; for(int i=0;i<n-1;i++){ int ind=n-2-i; int d=k/per[ind]; k=k%per[ind]; for(int j=0;j<9;j++){ if(vvv[j]!=-1){ if(d!=0)d--; else{ ret+='0'+vvv[j]; vvv[j]=-1; break; } } } } for(int j=0;j<9;j++){ if(vvv[j]!=-1){ ret+='0'+vvv[j]; vvv[j]=-1; break; } } return ret; } };
View Code
相关文章推荐
- (1.1.9)UVA 10930 A-Sequence(模拟)
- ArrayBlockingQueue使用
- 关于在SLES11, RHEL6, OEL6 and UEK2 Kernels使用hugepages的告警
- STL总结之queue, priority_queue, stack
- STL总结之deque
- POJ 1141 Brackets Sequence ( 区间DP )
- 从Alarm看Android上层UI到内核代码的流程分析 .
- UVA10405-Longest Common Subsequence && nyoj36-最长公共子序列
- Flash Builder 入门
- String,StringBuffer,StringBuilder,寻找最大相同字符串
- hud 1509 Windows Message Queue 简单优先队列
- LES DIFFIRENTS DE QUE ET QUEL
- QUEUE——队列(procedure)
- IPhone UIButton 属性
- 如何从 Internet 获得 Request for Comments 文档
- win7 64 arduino driver 安装失败的总结
- RobocupRescue烂尾代码
- uestc 1307 windy数
- Code Forces Round 201 B Lucky Common Subsequence 拓展提问
- Ad Hoc Distributed Queries的启用与关闭