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. django 查询集 API

    filter 表示=, 返回一个新的QuerySet,包含与给定的查询参数匹配的对象.exclude 表示!=. 返回一个新的QuerySet,它包含不满足给定的查找参数的对象. annotate 使 ...

  2. yum安装Apache,Mysql,PHP

    用yum安装Apache,Mysql,PHP.  用yum安装Apache,Mysql,PHP. 2.1安装Apache yum install httpd httpd-devel 安装完成后,用/e ...

  3. Mono源码学习笔记:Console类(三)

    Buffer 类 (public static class) 以下就是 mcs/class/corlib/System/Buffer.cs: 001: // 002: // System.Buffer ...

  4. mysql only_full_group_by问题

    我的mysql出现了only_full_group_by问题,网上一堆处理方案! 主要两种 一种修改配置表my.ini 另一种通过指令,屏蔽当前链接的only_full_group_by报错!我想永久 ...

  5. makefile之call函数

    call函数是唯一一个可以创建定制化参数函数的引用函数. 支持对自定义函数的引用; 支持将一个变量定义为一个复杂的表达式,用call函数根据不同的参数对它进行展开来获取不同的结果; 函数语法: $(c ...

  6. PHPEXCEL在thinkphp中封装成类使用

    PHPEXCEL在thinkphp中封装成类使用 标签: phpexcel导出导入thinkphp -- : 435人阅读 评论() 收藏 举报 分类: php() 版权声明:本文为博主原创文章,未经 ...

  7. CSU 1329: 一行盒子

    1329: 一行盒子 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 740  Solved: 145[Submit][Status][Web Board ...

  8. 李洪强和你一起学习前端之(8)CSS复习

    今天是2017年3月24日周五 每一天都是余生当中最好的一天,珍惜当下. CSS基础复习 1 复习 1.1Css第一天 css层叠样式表 基础选择器 标签选择器 p{属性: 值;} 类选择器 .自定义 ...

  9. 本地运行storm时报错

    java.lang.NoClassDefFoundError: backtype/storm/topology/IRichSpout at java.lang.Class.getDeclaredMet ...

  10. javascript中的函数作用域和声明提前

    在一些类C的编程语言中,花括号内的每一段代码都具有各自作用域,并且变量在声明他们的代码段之外是不可见的,这个概念叫做块级作用域. javascript中没有块级作用域的概念,有的是函数作用域的概念:变 ...