leetcode
来源:互联网 发布:看电影用什么软件最好 编辑:程序博客网 时间:2024/06/10 02:13
Permutation Sequence
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.
Solution:
public String getPermutation(int n, int k) { List<Integer> numbers = new ArrayList<>(); int[] factorial = new int[n + 1]; StringBuilder sb = new StringBuilder(); int sum = 1; factorial[0] = 1; for (int i = 1; i <= n; i++) { sum *= i; factorial[i] = sum; } // factorial[] = {1, 1, 2, 6, 24, ... n!} for (int i = 1; i <= n; i++) { numbers.add(i); } // numbers = {1, 2, 3, 4} k--; for (int i = 1; i <= n; i++) { int index = k / factorial[n - i]; sb.append(numbers.get(index)); numbers.remove(index); k -= index * factorial[n - i]; } return String.valueOf(sb); }
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- GO类型查询
- PHP调用系统函数时报错未定义解决方法
- 上传图片,头像
- struts中的全局结果页面配置
- mysql性能优化(九) mysql慢查询分析、优化索引和配置
- leetcode
- 目标检测--Training Region-based Object Detectors with Online Hard Example Mining
- xutils3解析数据:
- CCF CSP 网络延时 树的直径
- 【图像处理】XMP Tags
- leetcode
- 一个通用的逗号分隔字符串转成各种数组的TypeHandler
- 银行小系统测试
- Unity5 雾化效果(一)