lintcode Permutation Index 排列序号
来源:互联网 发布:手机短信软件哪个好 编辑:程序博客网 时间:2024/05/16 06:09
排列序号
给出一个不含重复数字的排列,求这些数字的所有排列按字典序排序后该排列的编号。其中,编号从1开始。
样例
例如,排列 [1,2,4]
是第 1
个排列。
参考:http://www.mamicode.com/info-detail-1079668.html
思路:
1.对于四位数:4213 = 4*100+2*100+1*10+3
2.4个数的排列有4!种。当我们知道第一位数的时候,还有3!种方式,当知道第二位数时候还有2!种方式,当知道第三位数的时候还有1!种方式,前面三位数都确定的时候,最后一位也确定了。<这里是按照高位到地位的顺序>
3.对4个数的排列,各位的权值为:3!,2!,1!,0!。第一位之后的数小于第一位的个数是x,第二位之后的数小于第二位的个数是y,第三位之后的数小于第三的个数是z,第四位之后的数小于第四位的个数是w,则abcd排列所在的序列号:index = x*3!+y*2!+z*1!,<0!=0>
在数的排列中,小数在前面,大数在后面,所以考虑该位数之后的数小于该为的数的个数,这里我自己理解的也不是很透,就这样。
4.例如 4213;x= 3,y = 1,z=0,index = 18+2=20
123;x = 0,y=0,index = 0
321;x= 2,y=1,index = 2*2!+1*1! = 5
这里的下标是从0开始的。
public long permutationIndex(int[] permutation) {// Write your code herelong index = 0;long position = 2;// position 1 is paired with factor 0 and so is// skippedlong factor = 1;for (int p = permutation.length - 2; p >= 0; p--) {long successors = 0;for (int q = p + 1; q < permutation.length; q++) {if (permutation[p] > permutation[q]) {successors++;}}index += (successors * factor);factor *= position;position++;}index = index + 1;return index;}
0 0
- lintcode Permutation Index 排列序号
- **[Lintcode]Permutation Index II排列序号II
- 197.Permutation Index-排列序号(容易题)
- 198.Permutation Index II-排列序号II(中等题)
- LintCode 197. 排列序号
- lintcode ----排列序号
- LintCode:排列序号
- Lintcode 排列序号
- LintCode之排列序号
- 排列序号-LintCode
- 排列序号II-LintCode
- [Lintcode]Permutation Index
- lintcode Permutation Index
- [LintCode] Permutation Index I & Permutation Index II
- [LintCode 197] 排列序号(Python)
- Lintcode(198) Permutation Index II
- lintcode刷题——排列序号
- 排列序号
- servlet的config对象
- Python函数作用域和闭包
- Java中的Copy-On-Write容器
- 关于素数的线性筛法
- Codeforces 95E-Lucky Country
- lintcode Permutation Index 排列序号
- 虫食算 dfs+剪枝
- Just do IT
- 低功耗蓝牙(BLE)
- 推荐两款很安逸的离线API文档查询工具Dash和Zeal
- 三极管讲解
- 关于CENT OS 6.7 安装ORACLE11G的问题
- Java Character类
- Android中选择控件、自动填充、GridView控件的使用