博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode--Permutation Sequence
阅读量:4464 次
发布时间:2019-06-08

本文共 1844 字,大约阅读时间需要 6 分钟。

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):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

 

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

public class Solution {     /**	 * This is a trick problem. We need to use how a permutation is generated.
* Let us consider, for example, the first digit of the permutation.
* Number 1 on the first digit until (n - 1)! + 1-th permutation. and (n - 1)! is the last * permutation starts with 1. For the same reason 2*(n-1)! is the last permutation starts with * number 2 and so on. So, on the first digit of k-th permutation can be determined by * ((--k) / (n - 1)!). Recursively, we can find the other digits of the permutation.
* * @param n --int, the number of digits in the permutation. * @param k --int, the k-th permutation which is looking for. * @return String --the permutation. * @author Averill Zheng * @version 2014-06-14 * @since JDK 1.7 */ public String getPermutation(int n, int k) { List
num = new ArrayList
(); int count = 1; //add the number in the ArrayList and calculate the factorial for(int i = 0; i < n; ++i){ num.add((i + 1)); count *= (i + 1); } //decrease k by 1 --k; //find each digit of the permutation. StringBuffer stb = new StringBuffer(); for(int i = 0; i < n; ++i){ count /= (n - i); //select an item from the ArrayList and add to the permutation. After that remove //the digit from the ArrayList since it has been added to the permutation. int itemToBeAdded = num.remove(k / count); stb.append(itemToBeAdded); k %= count; } return stb.toString(); }}

  

  

转载于:https://www.cnblogs.com/averillzheng/p/3788735.html

你可能感兴趣的文章
C语言常见问题 如何用Visual Studio编写C语言程序测试
查看>>
Web用户的身份验证及WebApi权限验证流程的设计和实现
查看>>
hdu 2098 分拆素数和
查看>>
ECMAScript6-let与const命令详解
查看>>
iOS 使用系统相机、相册显示中文
查看>>
什么是敏捷设计
查看>>
SCSS的基本操作
查看>>
"安装程序无法定位现有系统分区" 问题解决
查看>>
.NET中栈和堆的比较
查看>>
【莫队】bzoj 3781,bzoj 2038,bzoj 3289
查看>>
如何优化limit
查看>>
几种常用数据库字段类型查询语句
查看>>
提高效率必须改掉的7种习惯
查看>>
Java判断语句中判断条件的执行顺序
查看>>
Windows平台下tomcat+java的web程序持续占cpu问题调试
查看>>
OO第四次博客作业!
查看>>
HDU 吉哥系列故事——完美队形II 騰訊馬拉松初賽第二輪D題
查看>>
[转]SQL Server 性能调优(io)
查看>>
设计模式学习-每日一记(6.原型模式)
查看>>
不已0开头的数字正则
查看>>