Permutation Sequence
2015-10-03 20:11
375 查看
题目:
The set
unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
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/
第二种:
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 ; StringBuilder buf = new StringBuilder(""); int[] res = new int ; 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(); }
相关文章推荐
- iOS图文攻略之UIView 属性
- Leetcode catalogue
- 关于queue和stack没有clear方法
- sqlite采用UUID主键和int型自增主键性能对比测试
- goquery使用
- UITextField  中文输入法
- Android UI 优化——使用HierarchyViewer工具
- 2015/10/3 iOS 笔记 细节 iOS9中UIAlertController的简单使用 ScrollView NSTimer
- Arduino2-库文件及基本函数
- 1007. Maximum Subsequence Sum (25)
- HDU5493 Queue【线段树】
- [UI]抽屉菜单DrawerLayout分析(三)
- 建造者模式与原型模式/builder模式与prototype模式/创建型模式
- Arduino1:中断知识点汇总
- [UI]抽屉菜单DrawerLayout分析(二)
- [UI]抽屉菜单DrawerLayout分析(一)
- ZOJ-3892- Available Computation Sequence
- iOS_UIAlertController
- pat1017Queueing at Bank (25)
- iOS之UI随笔-字典转模型以及双模型的构建