Permutation Sequence
来源:互联网 发布:无损音乐下载网站知乎 编辑:程序博客网 时间:2024/06/08 18:48
1.题目
给定 n 和 k,求123..n
组成的排列中的第 k 个排列。1 ≤ n ≤ 9
对于 n = 3
, 所有的排列如下:
123132213231312321
如果 k = 4
, 第4个排列为,231
.2.算法
public String getPermutation(int n, int k) { if (n <= 0) { return ""; } k--; StringBuilder res = new StringBuilder(); int factorial = 1; ArrayList<Integer> nums = new ArrayList<Integer>(); for (int i = 2; i < n; i++) { factorial *= i; } for (int i = 1; i <= n; i++) { nums.add(i); } int round = n - 1; while (round >= 0) { int index = k / factorial; k = k % factorial; res.append(nums.get(index)); nums.remove(index); if (round > 0) { factorial /= round; } round--; } return res.toString(); }
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
- VirtualBox(启动失败:intel_rapl no valid rapl domains found in package 0 error VirtualBox)
- 24.Interpreter-解释器模式
- 【干货分享】流程DEMO-人员调动流程
- B+树在数据库索引中的应用
- 《陈康二逼》
- Permutation Sequence
- 抽奖程序
- FutureTask 源代码深刻解读
- 拼接模型坐标系的理解(五)
- UIView层次切换(bringSubviewToFront,sendSubviewToBack)的使用
- 在 Node.js 中读写 Redis 的数据(失效时间和TTL) 【已翻译100%】
- Java 内存溢出(java.lang.OutOfMemoryError)的常见情况和处理方式总结
- 设计模式(一) 简单工厂模式
- C# 操控滚动条