Permutation Sequence
来源:互联网 发布:c语言打印日历头文件 编辑:程序博客网 时间:2024/06/10 01:06
Q:
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.
Solution:
public class Solution { public String getPermutation(int n, int k) { List<Integer> digits = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) digits.add(i); StringBuilder result = new StringBuilder(); for (int i = 0; i < n; i++) { int product = fac(n-1-i); int index = 0; while (k > product) { k = k - product; index++; } result.append(digits.remove(index)); } return result.toString(); } public int fac(int n) { int ret = 1; for (int i = n; i > 1; i--) ret = ret * i; return ret; }}
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
- 访问类的成员
- 私人列表
- 定义的顺序
- UVA 11584 - Partitioning by Palindromes
- C++读取文件单词计数
- Permutation Sequence
- Java基础-->集合框架
- Hadoop学习笔记(二)设置单节点集群
- Demo_TabHost+Fragment排版_141006
- HTML总结
- 重载<<运算符,以及隐式的类型转换函数
- 总结一下关于postgresql数据库的使用心得
- 哪个牌子的洁面仪比较好
- 机器学习手记[1]---朴素贝叶斯Naive Bayesian案例学习