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 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.
  • Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"

By observing the sequence for n = 3, we can see the permutation sequence is 1 + [2, 3] permutation, 2 + [1, 3] permutation, 3 + [1, 2] permutation. The sequence with first element = 1 has value k = 1, 2, with first element = 2 has value 3, 4, with first elemnt = 3 has value 5, 6, it's not hard to see that the index of the first element is (k-1)/2!

Next, we want to find the first element for n = 2, since there is only 2! permutation, the new k would be in the range [1, 2!],  if you observe the original k and the permutation:

[2, 3] k = 0 -> new k = 0

[3, 2] k = 1 -> new k = 1

[1, 3] k = 2 -> new k = 0

[3, 1] k = 3 -> new k = 1

[1, 2] k = 4 -> new k = 0

[2, 1] k = 5 -> new k = 1

new k = old k / 2!, it's just the same problem, with smaller n and k, hence we can use either recursive or iterative to solve it.

Key taken: --k, which makes the caculation easier also rules easier to observe, if k == 0, it's the first sequence in the permutation, no further work needed.

Time complexity: O(n*2)

Iterative:

public class PermutationSequenceLT60 {
private int calculateFactorial(int n) {
int factorial = 1;
for(int i = 2; i <= n; ++i) {
factorial *= i;
}
return factorial;
} public String permutation(int n, int k) {
StringBuilder result = new StringBuilder(); List<Integer> nums = new LinkedList<>();
for(int i = 1; i <= n; ++i) {
nums.add(i);
} int factorial = calculateFactorial(n); --k;
for(int i = n; k > 0 && i >= 1; --i) {
factorial = factorial/i;
int pos = k/factorial;
result.append(nums.remove(pos));
k = k%factorial;
} for(int num: nums) {
result.append(num);
} return result.toString();
} public static void main(String[] args) {
PermutationSequenceLT60 p = new PermutationSequenceLT60();
System.out.println(p.permutation(4, 9));
for(int i = 1; i <= 6; ++i) {
System.out.println(p.permutation(3, i));
}
for(int i = 1; i<= 24; ++i) {
System.out.println(p.permutation(4, i));
}
}
}

Recursive:

public class PermutationSequenceLT60 {
private int calculateFactorial(int n) {
int factorial = 1;
for(int i = 2; i <= n; ++i) {
factorial *= i;
}
return factorial;
} private void permutationHelper(int k, List<Integer> nums, StringBuilder result, int factorial) {
if(k == 0) {
for(int num: nums) {
result.append(num);
}
return;
} int pos = k/factorial;
result.append(nums.remove(pos));
permutationHelper(k%factorial, nums, result, factorial/nums.size());
} public String permutation(int n, int k) {
StringBuilder result = new StringBuilder(); List<Integer> nums = new LinkedList<>();
for(int i = 1; i <= n; ++i) {
nums.add(i);
} int factorial = calculateFactorial(n-1);
permutationHelper(k-1, nums, result, factorial); return result.toString();
} public static void main(String[] args) {
PermutationSequenceLT60 p = new PermutationSequenceLT60();
System.out.println(p.permutation(4, 9));
for(int i = 1; i <= 6; ++i) {
System.out.println(p.permutation(3, i));
}
for(int i = 1; i<= 24; ++i) {
System.out.println(p.permutation(4, i));
}
}
}

Permutation Sequence LT60的更多相关文章

  1. 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 序列排序

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

  3. Leetcode 60. Permutation Sequence

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

  4. 【leetcode】 Permutation Sequence (middle)

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

  5. 60. Permutation Sequence

    题目: The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of t ...

  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] “全排列”问题系列(二) - 基于全排列本身的问题,例题: Next Permutation , Permutation Sequence

    一.开篇 既上一篇<交换法生成全排列及其应用> 后,这里讲的是基于全排列 (Permutation)本身的一些问题,包括:求下一个全排列(Next Permutation):求指定位置的全 ...

  8. leetcode总结:permutations, permutations II, next permutation, permutation sequence

    Next Permutation: Implement next permutation, which rearranges numbers into the lexicographically ne ...

  9. Java for LeetCode 060 Permutation Sequence

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

随机推荐

  1. spring boot 代理(not eligible for auto-proxying)

    spring 事务机制网上的案例很多,关于事务 不能回滚也有很多的类型,不同的问题有不同的处理方案,本篇博客主要介绍两种事务不能回滚的问题解决方案: 问题一:    在同一个对象中有两个方法,分别未方 ...

  2. iftop网络流量查看工具

    1.下载iftop源码包 mkdir /usr/local/src/iftop cd /usr/local/src/iftop wget http://www.ex-parrot.com/~pdw/i ...

  3. SXSSExcelUtil

    package com.numa.util; import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.util ...

  4. cacti报ERROR: unknown option '--border' 解决方法

    cacti制图报下面提示 if (isset($rrdborder) && $rrdversion >= 1.4) { $graph_opts .= "--border ...

  5. Python基础之Python的变量、常量

    变量 看下面这个输出 print('整数达斯柯达敬爱的卡斯加大受打击啊') 变量:就是将运算的中间结果暂时存到内存中,以便后续代码调用 res = '整数达斯柯达敬爱的卡斯加大受打击啊') print ...

  6. python--第四天总结

    lambda表达式 处理简单函数自动返回 学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即: # 普通条件语句 if 1 == 1: name = 'wupeiqi' el ...

  7. DataGridView中DataGridViewComboBoxColumn的一些相关应用(一)让其值改变时触发事件-转

    转自  https://maodaili.de/mao.php?u=a%2FMrbEvUE8PnCuc7FrhJi0Rqd3kmOBHPZUbcJ1c2hbJUK0RYWpAf4lhIOddItP%2 ...

  8. java面试题:多线程与并发

    多线程 关键词:线程池 Q:如何新建一个线程? 继承Thread,或者实现Runnable接口,或者通过Callable接口实现. Q:Callable怎么用? Callable可以作为FutureT ...

  9. c/c++ 中的重要函数

    1,strtod: 函数原型: #include <cstdlib> double strtod(const char *nptr, char **endptr); strtod 原型 名 ...

  10. Java-分治算法

    一.分治算法的原理 分治算法就是将一个规模为N的问题分解成K个规模较小的子问题,这些子问题相互独立且与原问题性质相同,求出子问题的解,就可以得出原问题的解 二.分治算法的伪代码实现 合并算法Merge ...