Leetcode -- Permutation Sequence
来源:互联网 发布:linux snmp测试 编辑:程序博客网 时间:2024/06/05 14:52
https://oj.leetcode.com/problems/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.
public String getPermutation(int n, int k)
这题和next permutation其实是同一种数学逻辑,但这题和那题的做法关联并不大。更加靠近一种dp的思维:前一位的结果都是从后面的结果逐步推演的。
首先正如题目所言,n长度的set有n!的变化。那么往下推理可得 n - 1 长度的set就会有n - 1!的变化。n - 2长度的set 就会有n - 2!的变化。
这意味着一个很重要的东西。假如我们把n个长度的set分解为一个1个长度的set和一个n - 1长度的set,譬如1,2,3,4,5... n看成 [1]和[2,3,4,...n]的两个set。那么什么时候1会变成2呢,那就是当[2,3,4...n]完成了n - 1!种变化之后,如果把[1,2,3...n]分解成[1][2][3...n]三个set,那么俄什么时候变成3呢,那就是[3...n]完成了n - 3!次变化之后。如此类推。那么接下来如何求解就很好理解了。第一个元素就是k / (n - 1)! + 1, 然后k = k % (n - 1)!, 第二个元素实际上再就是 k = k / (n - 2)! + 1,然后k = k % (n - 2)!...如此往下类推。当然,我们需要考虑到同一个元素不能出现两次,所以刚才元素求解出来的其实是表示当前剩余元素根据排序之后得到的index。根据以上算法,给出代码如下:
public String getPermutation(int n, int k) { int k_factorial = 1; for(int i = 2; i < n; i++){ k_factorial *= i;//首先我们需要得到(n - 1)! } ArrayList<Integer> num = new ArrayList<Integer>(); for(int i = 0; i < n; i++) num.add(i + 1);//这里我们用一个数组来筛选每一位的元素和保留剩余未选的元素 StringBuilder res = new StringBuilder(); k--; for(int i = 0; i < n; i++){ int an = k / k_factorial;//得到当前位的index所在 k = k % k_factorial;// 为下一位做准备 if(n - i - 1 != 0) k_factorial /= (n - i - 1);// 将(n - k)! 变成(n - k - 1)! 为下一次运算做准备。 res.append(num.get(an)); num.remove(an);//当前被选中的元素就要从buff里去掉了 } return res.toString(); }
- LeetCode: Permutation Sequence
- LeetCode Permutation Sequence
- [Leetcode] Permutation Sequence
- [LeetCode] Permutation Sequence
- leetcode 74: Permutation Sequence
- leetcode Permutation Sequence
- [leetcode] Permutation Sequence
- [LeetCode]Permutation Sequence
- LeetCode:Permutation Sequence
- LeetCode-Permutation SequencePermutation Sequence
- [leetcode] Permutation Sequence
- LeetCode - Permutation Sequence
- LeetCode:Permutation Sequence
- LeetCode 60: Permutation Sequence
- Leetcode: Permutation Sequence
- leetcode Permutation Sequence
- LeetCode | Permutation Sequence
- LeetCode Permutation Sequence
- qq空间营销快速排名技巧
- 根据时间搜索数据
- SQL SERVER与oracle中的递归处理
- 脚本式计算能力对报表工具的重要性
- IOS中Json解析的四种方法
- Leetcode -- Permutation Sequence
- 自己写 Netfilter 匹配器
- Swift应用开源项目推荐
- IE及标准浏览器中DIV居中问题
- ubuntu 下apt-get 命令
- android 旋转动画
- CV牛人牛事简介之一
- online_judge_1167
- java 优化 笔记