Permutation Sequence
来源:互联网 发布:linux telent 安装 编辑:程序博客网 时间:2024/05/27 20:50
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.
Have you met this question in a real interview?
思路: 这个排列是按照 (n - 1) ! 来排列的, 每一层都有( n - 1 ) ! 个 数字, 因此我们要找到是第 selectI 个 要先 除以 (n - 1) !, 然后找到在没使用的数字中 的 第 selectI 个 数字, 并设置为已经使用。 最后如果 到了 第1 个,把剩余的没使用的数字按顺序插入。
易错点: 1 . k 一开始要 减1 。
2. level 每次 要除以 n - i ; i 从1 到 n - 1
public class Solution { public String getPermutation(int n, int k) {boolean[] used = new boolean[n + 1];StringBuilder buffer = new StringBuilder();used[0] = true;int level = 1;for (int i = 1; i < n; ++i) {level *= i;// 阶乘的当前level }k = k - 1;//-----非常重要for (int i = 1; i < n; ++i) {int selectI = k / level;for(int j = 1; j <= n; j++){if(!used[j]){selectI--;}if(selectI == -1){used[j] = true;buffer.append(j);break;}}k = k % level;//-----level /= (n - i);//--- 从 n - 1 , 除到 1, 阶乘 反向除下去}for(int i = 1; i <= n; i++){// 把还没用过的数字按顺序 插入if(!used[i]){ used[i] = true;buffer.append(i);break;}}return new String(buffer);}}
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
- [编程语言][C语言]C语言的顺序结构
- 在CentOS 6.5上安装软件
- nginx反向代理配置,负载均衡
- C中如何调用C++函数、类内函数
- jdk安装配置
- Permutation Sequence
- Linux C调用C++库
- 数组越界导致的运行崩溃(枚举作为数组中的常量)
- jQuery学习
- iOS 8 模拟器键盘无法弹出
- c头文件一览表
- python压缩zip文件
- LinearLayout addView 应该是这样写的.
- 总结14,展望15