Permutation Sequence
来源:互联网 发布:2016淘宝活动报名入口 编辑:程序博客网 时间:2024/05/22 00:07
一开始用DFS,搜索,结果超时了。后来想想 这种算法确实不好。就想到了下面的算法:
假设n= 5,k = 100;
先考虑第一位数应该是什么,第一位如果是5xxxx,那么前面应该有4!*4 = 96个数,k>96所以第一位确定为5
第二位数,如果是54xxx,那么考虑第二位前面应该有3!*3 = 18个数,k<18+96,考虑53xxx,由此继续……
class Solution {private: string ans; int a[9];public: string getPermutation(int n, int k) { int *pow = new int[n+1]; pow[0] = 1; for(int i = 1;i<=n;i++) { pow[i] = pow[i-1]*i; } string ans = ""; bool *isUsed = new bool[n+1];//这里为了方便将他初始化为n+1位 memset(isUsed,false,sizeof(bool)*(n+1)); for(int i = n;i>0;i--) for(int j = n;j>0;j--) { if(!isUsed[j]) { int count = 0; for(int m = 1;m<=n;m++) if(!isUsed[m]&&m<j) count++; if(pow[i-1]*count<k) { k -= pow[i-1]*count; ans += (char)(j+'0'); isUsed[j] = true; break; } } } return ans; }};
0 0
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- 深入Mysql字符集设置
- codeforces 06/01/B The Child and Set
- #250 div.2 A. The Child and Homework
- azure云配置ubuntu虚拟机及部署scrapy
- linux 学习之路(学linux必看)
- Permutation Sequence
- 黑马程序员-JAVA面向对象封装、继承和多态
- Android中Preference的使用以及监听事件分析
- 网络虚拟化技术
- Light OJ 1334 Genes in DNA KMP+DP
- POJ训练计划3687_Labeling Balls(拓扑排序)
- 如何将Win8的默认窗口背景设为护眼色(彻底)
- kernfs_link_sibling
- Mongodb地理空间索引