leetcode解题方案--060--Permutation Sequence
来源:互联网 发布:数据库范式例题 编辑:程序博客网 时间:2024/06/14 05:15
题目
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.
分析
我的思路很奇怪
用递归。
- 先判断第k个排序会影响到哪一位
- 得到三个值,分别代表变动的数字个数,前一位增长值和下一次递归的k
class Solution { public static String getPermutation(int n, int k) { k = k-1; int [] cons = new int[11]; cons[0] = 1; cons[1] = 1; for (int i = 2; i<=10; i++) { cons[i] = i*cons[i-1]; } int[] array = new int[n]; for (int i =0; i<n; i++) { array[i] = i+1; } StringBuffer ret = new StringBuffer(""); getkIndex(ret, array, k, cons); return ret.toString(); } public static void getkIndex(StringBuffer xx, int[] array, int k, int[] cons) { Arrays.sort(array); int length = array.length; if (length ==1) { xx.append(array[0]); return; } else if (length == 0) { return; } int variNum = 0; int nextK = 0; int increase = 0; for (int i =0; i<length; i++) { if (k<cons[i+1]) { variNum = i; nextK = k%cons[i]; increase = k/cons[i]; break; } } int tmp = array[length-variNum-1]; array[length-variNum-1] = array[length-variNum-1+increase]; array[length-variNum-1+increase] = tmp; for (int i = 0; i< length-variNum; i++) { xx.append(array[i]); } int[] nestArray = new int[variNum]; System.arraycopy(array, length-variNum, nestArray, 0, variNum); getkIndex(xx, nestArray, nextK, cons); }}
阅读全文
0 0
- leetcode解题方案--060--Permutation Sequence
- LeetCode 060 Permutation Sequence
- LeetCode 060 Permutation Sequence
- LeetCode 060 Permutation Sequence
- leetcode之Permutation Sequence解题思路
- [leetcode] 60. Permutation Sequence 解题报告
- [Leetcode] 60. Permutation Sequence 解题报告
- [leetcode]60. Permutation Sequence@Java解题报告
- Leetcode #60. Permutation Sequence 排列组合序列 解题报告
- leetcode 060 —— Permutation Sequence
- leetcode:数学:Permutation Sequence(060)
- LeetCode: Permutation Sequence
- LeetCode Permutation Sequence
- [Leetcode] Permutation Sequence
- [LeetCode] Permutation Sequence
- leetcode 74: Permutation Sequence
- leetcode Permutation Sequence
- [leetcode] Permutation Sequence
- 形态学操作
- json 得到 第一个 对象的 属性
- Apache系列—Windows不能在本地计算机启动Apache
- 一篇对JS的重新介绍
- oracle 建表
- leetcode解题方案--060--Permutation Sequence
- 遇见kafka
- 瑞昱 rtl8710 试用
- eoj 1816. 连通(无向图是否连通判定)
- tomcat启动了两次,导致mina监听的端口报端口被占用的错误
- r语言安装错误
- VS2013 +QT5.7+QGIS2.18
- linux系统安装VNC服务端
- JZOJ5484. 【清华集训2017模拟11.26】快乐树