Permutation Sequence
来源:互联网 发布:锐思数据库 编辑:程序博客网 时间:2024/05/01 17:11
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.
就是给你一个数字范围,让你求第k个排列
一开始想的是直接上来递归模拟,没想太多,只不过,阶乘这个东西的增长速度实在太快了,我都没有料到9的阶乘竟然可以达到362880.。。。在这里也当个教训
看到Note就大致知道了该怎么去模拟这道题
思路:
如果n=4,k=5
5<3!
所以第一个数字肯定是1,把1从vector里删除
继续5>2! 所以k = 5-2 = 3
3>2! k = 3-2 = 1
减了2次,所以第二个数字应该选vector里面的下标为2的元素,即4
第三个
1=1! ,所以第三个数字直接选vector里面下标为0的元素,即2
第四个数字时,vector里面只剩下一个元素,所以第四个为3
即1 4 2 3
class Solution {public: int num[8] = {1,2,6,24,120,720,5040,40320}; string getPermutation(int n, int k) { vector<int> v; for(int i=0;i<n;i++) v.push_back(i+1); string shit = ""; int cur = 0; while(k>0){ int idx = 0; if(n-2-cur<0){ k--; }else{ while(k>num[n-2-cur]){ k-=num[n-2-cur]; idx++; } } char c = v[idx]+'0'; vector<int>::iterator it = v.begin()+idx; v.erase(it); shit+=c; cur++; } return shit; }};
直接打表出到8的阶乘
ac
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
- trun off PInvokeStackImbalance
- 关于java web后台开发的一点心得
- 二叉树后序遍历
- android 禁止休眠和锁屏
- 写在2013的尾巴 即 写在蛇年的尾巴
- Permutation Sequence
- Unity自动寻路的简单演示
- hdu 4699 Editor 伸展树 treap复习
- 小白dp uva 662 - Fast Food (除夕夜的博客 ^ ^)
- JobQueueTaskScheduler
- CentOs 安装gcc 4.8.1
- UVA 11461 - Square Numbers 数学水题
- C++学习日记4 C++常量和算术表达式
- 罗大柚OpenGL ES教程系列LessonOne(Part 1): 绘制一个三角形