算法<Permutation Sequence>
来源:互联网 发布:nestopia mac 编辑:程序博客网 时间:2024/05/29 03:46
问题描述:给定1-n个整数,将这N个数字做全排列,求第K个排列,结果用String形式返回。
分析:
对于{1,2,3,4}的全排列来说,可以是:
1+{2,3,4}的全排列;
2+{1,3,4}的全排列;
3+{1,2,4}的全排列;
4+{1,2,3}的全排列;
假如我们要求第十五个全排列,那么我们的流程应该是
k=15-1
i=1;14/3!=2=>数组{1,2,3,4}中第三个数字是3,将数组中的3除去,此时数组为{1,2,4};更新K=14-2*3!=2;
k=2
i=2;2/2!=1=>数组{1,2,4}中的第二个数字是2,将3从数组中得到新的数组{1,4};
….
最后可以得到结果:3214
思路已经理清楚,接下来就是代码的实现了:
import java.util.ArrayList;import java.util.List;/** * 给定一个n,在从1-n的数字的 全排列中找到第k个全排列 * * @version 2017/7/21.21:33 */public class K_th_Permutation { public static void main(String[] args) { System.out.println(new K_th_Permutation().getPermutation(4, 15)); } public String getPermutation(int n, int k) { List<Integer> list = new ArrayList<>(); int[] factorial = new int[n + 1]; StringBuilder builder = new StringBuilder(); // create an array of factorial lookup //求n的阶乘 int sum = 1; factorial[0] = 1; for (int i = 1; i <= n; i++) { sum *= i; factorial[i] = sum; } // factorial[] = {1, 1, 2, 6, 24, ... n!} // create a list of list to get indices for (int i = 1; i <= n; i++) list.add(i); // list = {1, 2, 3, 4} k--; for (int i = 1; i <= n; i++) { int index = k / factorial[n - i]; builder.append(String.valueOf(list.get(index))); list.remove(index); k -= index * factorial[n - i]; } return String.valueOf(builder); }}
阅读全文
0 0
- Permutation Sequence算法详解
- 算法<Permutation Sequence>
- Leetcode算法学习日志-60 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
- 顺序分数
- servlet_JSP
- Spring 菜鸟笔记
- codeforces- 82B
- (2)创建一个服务和消息
- 算法<Permutation Sequence>
- Ubuntu常用命令
- 算法-->顺序查找
- 1.用户/执行/文件系统/ls/cd
- GoF23设计模式(0)单例模式Singleton
- 15.Scala多重继承、多重继承构造器执行顺序及AOP实现
- 【codefoces821E】 Okabe and El Psy Kongroo【Dp+矩阵快速幂】
- Android 新手安装Eclipse 启动后的主界面没有出现 SDK manager 的图标
- Python 字符串