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. springboot 集成 redis

    导入maven依赖 <!-- springboot整合 redis --> <dependency> <groupId>org.springframework.bo ...

  2. Dictionary在多线程情况下

    Add时出错 错误信息: Index was outside the bounds of the array. 详细信息: at System.Collections.Generic.Dictiona ...

  3. target=_blank攻击

    [target=_blank攻击] 在<a>标签中加入 rel="noopener noreferrer" 来避免. 参考:https://mathiasbynens. ...

  4. python--第三天总结

    [collection系列]1.计数器(counter) Counter是对字典类型的补充,用于追踪值的出现次数. ps:具备字典的所有功能 + 自己的功能 c = Counter('abcdeabc ...

  5. 每月IT摘录201810

    技术 1.Redis.对于单机实例,我们采用原生主从(Master-Slave)模式实现高可用,常规模式下对外仅暴露 Master 节点.由于使用原生 Redis,所以单机实例支持所有 Redis 指 ...

  6. poj2970 The lazy programmer 【优先队列】

    A new web-design studio, called SMART (Simply Masters of ART), employs two people. The first one is ...

  7. Jenkins安装部署(二)

    Jenkins配置 一.修改jenkins家目录 由于jenkins在启动个之后会默认将所有的构建应用在家目录中创建一遍,为了合理化服务器资源,重新定义jenkins家目录. 在tomcat的cata ...

  8. 最近读jdk源码一些基础的总结(有待后续深入)

    第一点:java.lang 1.Object类,hashCode()方法,equals()方法,clone()方法,toString()方法,notify()和notifyAll()方法,wait() ...

  9. RocketMq --consumer自动实现负载均衡

    这边使用一个producer和两个consumer是实现负载均衡. 看一下代码示例 package com.alibaba.rocketmq.example.message.model; import ...

  10. @RequestBody使用须知

    -----------------------siwuxie095                                 @RequestBody 使用须知         使用 @Requ ...