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.

Newest Solution, a much shorter one:

public class Solution {
public String getPermutation(int n, int k) {
boolean[] used = new boolean[n]; int index = n;
int total = 1;
for (int i=1;i<=n;i++){
total *= i;
}
StringBuilder builder = new StringBuilder();
while (index!=0){
total = total / index;
int count = (k-1) / total + 1;
k = (k-1) % total + 1;
int ind = 0;
for (int i=0;i<n;i++)
if (!used[i]){
ind++;
if (ind==count){
used[i] = true;
builder.append(i+1);
break;
}
}
index--;
}
return builder.toString();
}
}

Solution 1:

We use recursive method to get the sequence one by one. However, this method is slow.

 public class Solution {
public String getPermutation(int n, int k) {
int[] seq = new int[n+1];
int level = 1;
boolean[] used = new boolean[n+1];
Arrays.fill(used,false);
Arrays.fill(seq,0);
used[0] = true;
int count = 0;
String res = "";
while (true){
if (level==n){
count++;
if (count==k){
for (int i=1;i<=n;i++)
if (!used[i]){
seq[level] = i;
break;
}
for (int i=1;i<=n;i++)
res += Integer.toString(seq[i]);
break;
} else {
level--;
continue;
}
} int val = seq[level];
//NOTE: we need the first condition, because used array does not have n+1.
while (val<n+1 && used[val])
val++;
if (val==n+1){
if (seq[level]!=0) used[seq[level]] = false;
seq[level]=0;
level--;
continue;
} else {
if (seq[level]!=0) used[seq[level]] = false;
seq[level] = val;
used[val]=true;
level++;
}
} return res; }
}

Solution 2:

We actually can calculate the sequence. For sequences with n numbers, it is composed by n segments of sequences with n-1 numbers. The number of (n-1) sequences in each segment is (n-1)!. So if we are looking for kth n sequence, it is in (k/(n-1)!)th or (k/(n-1)!+1)th segment (boundary case considerred) which is means the number in the first place should be the (k/(n-1)!)th available number between 1 and n. The number of sequences we should count in this segment to find the target is (k%(n-1)!)th sequence in this segement. With this recurrence formula, we can directly calculate the string one place by one place.

NOTE: We need to consider the boundary cases where k%(n-1)!==0, in this case, it is the (n-1)!th sequence in the k/(n-1)! segment.

 public class Solution {
public String getPermutation(int n, int k) {
int[] seq = new int[n+1];
boolean[] used = new boolean[n+1];
Arrays.fill(used,false);
Arrays.fill(seq,0);
String res = "";
int[] val = new int[n+1];
val[0] = 0;
val[1] = 1;
for (int i=2;i<=n;i++)
val[i] = val[i-1]*i; int left = k;
int num = n;
for (int i=1;i<n;i++){
int interval = val[num-1];
int step = left/interval;
int nextLeft = left%interval;
if (nextLeft==0)
nextLeft = interval;
else step++;
int index=0;
for (int j=1;j<=n;j++)
if (!used[j]){
index++;
if (index==step){
seq[i]=j;
used[j] = true;
break;
}
}
left = nextLeft;
num--;
}
for (int i=1;i<=n;i++)
if (!used[i]){
seq[n]=i;
break;
} for (int i=1;i<=n;i++)
res += Integer.toString(seq[i]);
return res; }
}

Leetcode-Permuation Sequence的更多相关文章

  1. [LeetCode] Permutation Sequence 序列排序

    The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the p ...

  2. [leetcode]Permutation Sequence @ Python

    原题地址:https://oj.leetcode.com/submissions/detail/5341904/ 题意: The set [1,2,3,…,n] contains a total of ...

  3. LeetCode: Permutation Sequence 解题报告

    Permutation Sequence https://oj.leetcode.com/problems/permutation-sequence/ The set [1,2,3,…,n] cont ...

  4. LeetCode——Permutation Sequence

    The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and labeling all of the p ...

  5. [LeetCode]444. Sequence Reconstruction

    Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. Th ...

  6. [Leetcode] Permutation Sequence

    The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the p ...

  7. LeetCode OJ--Permutation Sequence *

    求第k个排列. 刚开始按照一个排列一个排列的求,超时. 于是演算了一下,发下有数学规律,其实就是康托解码. 康托展开:全排列到一个自然数的双射 X=an*(n-1)!+an-1*(n-2)!+...+ ...

  8. 【LeetCode】60. Permutation Sequence 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  9. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  10. Solution to LeetCode Problem Set

    Here is my collection of solutions to leetcode problems. Related code can be found in this repo: htt ...

随机推荐

  1. golang中使用mongodb的操作类以及如何封装

    mgo简介 mongodb官方没有关于go的mongodb的驱动,因此只能使用第三方驱动,mgo就是使用最多的一种. mgo(音mango)是MongoDB的Go语言驱动,它用基于Go语法的简单API ...

  2. 各种MQTT server功能比較

    this page attempts to document the features that various MQTT servers (brokers) support. This is spe ...

  3. SSH整合简单例子

    说明:简单SSH整合,struts版本2.3.32,spring版本3.2.9,hibernate版本3.6.10 一.开发步骤 1 引jar包,创建用户library.使用的包和之前博文相同,可以参 ...

  4. 查询MySql数据库架构信息:数据库,表,表字段

    /*1.查询所有数据库*/ show databases;  /*2.查询所有数据表*/ select * from information_schema.tables where table_sch ...

  5. CentOS6.x修改主机名,关闭防火墙

    一.centos默认主机名为localhost,不方便管理,此次,我修改为noi. 1.修改网络配置文件:/etc/sysconfig/network 首先,备份一下源文件,注意date命令和加号之间 ...

  6. 安装Eclipse插件长时间卡在 calculating requirements and dependencies

    把"Contact all update sites during install to find required software"前面的勾去掉,然后点击下一步,这样之后问题迎 ...

  7. 2018.5.2(7:20到的办公室开始早课 阮一峰的JS) 所有的默默努力都是为了让自己看起来毫不费力

    continue语句用于立即终止本轮循环,返回循环结构的头部,开始下一轮循环. break语句用于跳出代码块或循环. 标签(label) JavaScript 语言允许,语句的前面有标签(label) ...

  8. 扫目录过狗过waf方法

    用御剑的朋友都遇到过这个页面吧,装狗了开启保护就会这样 本机搭建安全狗设置发现,默认是过蜘蛛的,所以只要把http头来路改成蜘蛛的useragent就ok了 无奈御剑和wscan 都是无法设置http ...

  9. 修复Win10下Synaptics触摸板双指触击无法打开右键菜单的问题

    从Win8.1开始,Synaptics触摸板驱动的键值就不能正确设置,使得双指触击失效,无法打开右键菜单. 解决方法1.打开注册表:2.搜索“2FingerTapAction”,或直接定位到以下两个路 ...

  10. Centos版本 32或64位查看命令

    [root@root nginx]# uname -a Linux root -.el6.x86_64 # SMP Fri Nov :: UTC x86_64 x86_64 x86_64 GNU/Li ...