Permutation Sequence
来源:互联网 发布:lol请检查网络连接 编辑:程序博客网 时间:2024/06/05 19:35
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.
给定所有排列集合按升序排列,公用n!=n*(n-1)个。那么第一个数字为 k/(n-1)! 剩下的为k%(n-1)! 一直到最后一位。
code第九行用的是k-1, 我认为是归纳的结果,网上的说为了迎合0-n-1的说法,我没明白。 我们在计算第一位 去集合 k=[1,2,3,4,5,6] 对应第一位集合 为 [0, 0, 1, 1, 2, 2]。 如果不用k-1,那就是 [0, 1, 1, 2, 2, 3], 所以k-1刚好凑出来。。。。反正我是没想明白别的解释。。。
class Solution {public: string getPermutation(int n, int k) { string candidate=string("123456789").substr(0,n); string res(n,'0'); int fac=factor(n); for (int i=0; i<n; i++){ fac/=n-i; /* (n-1)! */ int index=(k-1)/fac; /*indexing the k to adapt with 0-n-1*/ res[i]=candidate[index]; candidate.erase(index,1); k-=index*fac; } return res; } /* calculate n!*/ int factor(int n) { int mult=1; for(int i=2; i<=n; i++) mult*=i; return mult; }};
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
- BASH 数组用法小结
- 清除数据库中的HTML格式
- 纯CSS写三角形-border法
- MFC 基础控件1,2
- iOS集成第三方登录(SSO授权登录<无需密码>
- Permutation Sequence
- windows远程ubuntu花屏
- 清除数据库中的HTML格式
- 禁用Mac键盘特殊字符
- 在vs2012中重载OnInitDialog
- 在xml中定义直线路径Custom straight line path in xml
- easyui--form load 异步变同步
- JVM监控与调优
- 网络基本功(十八):细说tcpdump的妙用(下)