(Java)LeetCode-60. Permutation Sequence
来源:互联网 发布:php trait 编辑:程序博客网 时间:2024/06/05 15:27
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的数的全排列,第一个数确定之后,剩下的数共有(n-1)!种可能性。所以要计算出第 kth 个全排列含有多少个(n-1)!了,比如有m个,那么第一个数就应该是m+1. 之后再确定第二个数,和第一个思路一样,只不过k要变成 k - m * (n-1)! ,如此循环即可。
PS. 用一个布尔数组标记这个数是否被用过,用过的话直接跳过。代码如下:
public class Solution { public String getPermutation(int n, int k) {int[] fac = { 1,1,2,6,24,120,720,5040,40320,362880};boolean[] flags = new boolean[n];StringBuilder st = new StringBuilder();getPermutation(st, flags, fac, n, k); return st.toString(); }private void getPermutation(StringBuilder st, boolean[] flags, int[] fac, int n, int k) {// TODO Auto-generated method stubwhile(true){if(n == 1){for(int i = 0; i < fac.length; i++ ){if(flags[i] == false){st.append(i+1);return;}}}int level = (k-1)/fac[n-1];k = k - level * fac[n-1];for(int i = 0; i < fac.length; i++){if(flags[i] == false){if(level == 0){st.append(i+1);flags[i] = true;break;}level--;}}n--;}}}
0 0
- (Java)LeetCode-60. Permutation Sequence
- [LeetCode] 60. Permutation Sequence java
- [Leetcode] Permutation Sequence (Java)
- [LeetCode][Java] Permutation Sequence
- [leetcode]60. Permutation Sequence@Java解题报告
- LeetCode --- 60. Permutation Sequence
- [Leetcode] 60. Permutation Sequence
- [leetcode] 60.Permutation Sequence
- **LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- [LeetCode]60. Permutation Sequence
- LeetCode *** 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- leetcode:60. Permutation Sequence
- [Leetcode] 60. Permutation Sequence
- [leetcode] 60. Permutation Sequence
- 我的第一篇博客啊,欢迎吐槽啦啦啦
- Erdaicms旅游网站程序源码V1.7正式发布
- 总结5
- MySql权限表
- ubantu kylin原始密码问题
- (Java)LeetCode-60. Permutation Sequence
- Reverse Integer
- Android Matrix的用法总结
- 最美江南小镇<朱家角>,你会带她去吗?
- 【微信开发】-发送位置进行Geocoding API转换(经纬度和地址名称互换), 主要代码在private function receiveLocation($object)
- session的removeAttribute()和invalidate()的区别
- 设计模式笔记 – Proxy 代理模式 (Design Pattern)
- windows下winscp连接不上ubuntu
- 【解决】unable to open database file