Permutation Sequence
来源:互联网 发布:淘宝客是做什么的 编辑:程序博客网 时间:2024/06/09 21:19
题目:
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.
分析:
第一位每个数字开头的序列都有(n-1)!个序列,因此n个数字所以共有n!个序列。
以此类推,第二位每一个数开头都有(n-2)!个序列。
参考代码如下:
http://www.programcreek.com/2013/02/leetcode-permutation-sequence-java/
public class Solution {public String getPermutation(int n, int k) {boolean[] output = new boolean[n];StringBuilder buf = new StringBuilder(""); int[] res = new int[n];res[0] = 1; for (int i = 1; i < n; i++)res[i] = res[i - 1] * i; for (int i = n - 1; i >= 0; i--) {int s = 1; while (k > res[i]) {s++;k = k - res[i];} for (int j = 0; j < n; j++) {if (j + 1 <= s && output[j]) {s++;}} output[s - 1] = true;buf.append(Integer.toString(s));} return buf.toString();}}
第二种:
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 %= 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
- Hibernate4在开发当中的一些改变
- 更新Podfile时半天没反应解决方案
- Java Web SSH-Hibernate框架复习
- Android Animation无限循环动画
- sjtu-acm-1033
- Permutation Sequence
- ZOJ 1221Risk_Floyd - Dijkstra
- unix高级编程
- GDataXMLNode应用
- codeforces 455C C. Civilization(树形dp+树的直径+并查集)
- 【设计模式】里氏代换
- 数据结构——概论
- 搭建tomcat服务器,目标可通过外网ip访问本机
- ORMLite框架(1)——入门用法