首页 > 代码库 > [leetcode] Permutation Sequence
[leetcode] 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.
https://oj.leetcode.com/problems/permutation-sequence/
计算1~n数字的第k个排列
思路1:从小到大生成同时计数,直到第k个。 肯定超时试都不用试。。
思路2:直接根据规律计算第k个排列。
分析:1~n个数共有n!个排列,1开头的有(n-1)!个,2开头的(n-1)!个,...n开头的有(n-1)!个。因此用k/(n-1)!就确定了第一位数字,然后依次类推(用过的数字要去除),继续在(n-1)!个数中找第k%(n-1)!个数。
思路2代码:
public class Solution { public String getPermutation(int n, int k) { int[] num = new int[n]; int permSum = 1; for (int i = 0; i < n; i++) { num[i] = i + 1; permSum *= (i + 1); } StringBuilder sb = new StringBuilder(); k--;//change to base 0 for (int i = 0; i < n; i++) { permSum = permSum / (n - i); int selected = k / permSum; sb.append(num[selected]); for (int j = selected; j < n - i - 1; j++) num[j] = num[j + 1]; k = k % permSum; } return sb.toString(); } public static void main(String[] args) { System.out.println(new Solution().getPermutation(4, 10)); }}
参考:
http://blog.csdn.net/havenoidea/article/details/12837441
http://www.cnblogs.com/TenosDoIt/p/3721918.html
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。