lintcode-easy-Permutation Index
2016-03-03 13:02
302 查看
Given a permutation which contains no repeated number, find its index in all the permutations of these numbers, which are ordered in lexicographical order. The index begins at 1.
Given [1,2,4], return 1.
思路:
统计最高位之后最高位数小的个数,(n-1)!乘以这个数,就得到最高位比现在的数最高位小的时候的所有组合数。再把最高位去掉,重复这个过程,就得到了结果。
Given [1,2,4], return 1.
思路:
统计最高位之后最高位数小的个数,(n-1)!乘以这个数,就得到最高位比现在的数最高位小的时候的所有组合数。再把最高位去掉,重复这个过程,就得到了结果。
public class Solution { /** * @param A an integer array * @return a long integer */ public long permutationIndex(int[] A) { // Write your code here if(A == null || A.length == 0) return (long) 0; long result = 0; for(int i = 0; i < A.length; i++){ long num = 0; for(int j = i + 1; j < A.length; j++){ if(A[j] < A[i]) num++; } result += num * fac(A.length - i - 1); } return result + 1; } public long fac(int num){ if(num == 0 || num == 1) return 1; long result = 1; for(int i = 1; i <= num; i++) result *= i; return result; } }
相关文章推荐
- 【poj1895】Bring Them There 分层图最大流
- AForge.NET .NET2.0程序集无法在.net 4.0 中运行的解决方案
- 1006: 开心的金明
- ubuntu14.10+QT4编写ARM9(mini2440)应用的配置与安装
- 转载 SharePoint 2013配置Master Page and Page Layout
- Css 动画的回调
- Android应用开发性能优化完全分析
- python 小知识
- 自动布局的基本用法
- 在SSIS 的 64 位版本中不支持 Excel 连接管理器[转]
- tee----把屏幕输出保存到文件
- 安卓MaterialDesign新特性,新控件FloatingActionButton,TabLayout,NavigationView等的使用
- 30行代码实现Javascript中的MVC
- 2016.3.3
- HDU 1010 Tempter of the Bone(dfs)
- Unity3D-启动unity事件,切换平台监听
- 杭电1058——Humble Numbers(丑数问题)
- C# 自己定义 implicit和explicit转换
- mybatis 关于 Parameter Maps collection does not contain value for
- HTTP API响应数据规范