|
| 1 | +package pp.arithmetic.medium; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by wangpeng on 2019-02-27. |
| 8 | + * 60. 第k个排列 |
| 9 | + * <p> |
| 10 | + * 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。 |
| 11 | + * <p> |
| 12 | + * 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: |
| 13 | + * <p> |
| 14 | + * "123" |
| 15 | + * "132" |
| 16 | + * "213" |
| 17 | + * "231" |
| 18 | + * "312" |
| 19 | + * "321" |
| 20 | + * 给定 n 和 k,返回第 k 个排列。 |
| 21 | + * <p> |
| 22 | + * 说明: |
| 23 | + * <p> |
| 24 | + * 给定 n 的范围是 [1, 9]。 |
| 25 | + * 给定 k 的范围是[1, n!]。 |
| 26 | + * 示例 1: |
| 27 | + * <p> |
| 28 | + * 输入: n = 3, k = 3 |
| 29 | + * 输出: "213" |
| 30 | + * 示例 2: |
| 31 | + * <p> |
| 32 | + * 输入: n = 4, k = 9 |
| 33 | + * 输出: "2314" |
| 34 | + * |
| 35 | + * @see <a href="https://leetcode-cn.com/problems/permutation-sequence/">permutation-sequence</a> |
| 36 | + */ |
| 37 | +public class _60_getPermutation_m { |
| 38 | + public static void main(String[] args) { |
| 39 | + _60_getPermutation_m getPermutation_m = new _60_getPermutation_m(); |
| 40 | + String permutation1 = getPermutation_m.getPermutation(3, 3); |
| 41 | + System.out.println(permutation1); |
| 42 | + String permutation2 = getPermutation_m.getPermutation(4, 9); |
| 43 | + System.out.println(permutation2); |
| 44 | + |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * 根据n阶乘的情况,按照有序算出K对应每一位的值 |
| 49 | + * |
| 50 | + * 执行用时: 11 ms, 在Permutation Sequence的Java提交中击败了81.62% 的用户 |
| 51 | + * 内存消耗: 37.3 MB, 在Permutation Sequence的Java提交中击败了3.26% 的用户 |
| 52 | + * |
| 53 | + * @param n |
| 54 | + * @param k |
| 55 | + * @return |
| 56 | + */ |
| 57 | + private String getPermutation(int n, int k) { |
| 58 | + char[] chars = new char[n]; |
| 59 | + int[] factorial = new int[n + 1]; |
| 60 | + for (int i = n; i >= 0; i--) { |
| 61 | + if (i == n) { |
| 62 | + factorial[i] = 1; |
| 63 | + } else { |
| 64 | + factorial[i] = factorial[i + 1] * (n - i); |
| 65 | + } |
| 66 | + } |
| 67 | + if (k > factorial[0]) { |
| 68 | + return ""; |
| 69 | + } |
| 70 | + List<Integer> numList = new LinkedList<>(); |
| 71 | + for (int i = 0; i < n; i++) { |
| 72 | + numList.add(i + 1); |
| 73 | + } |
| 74 | + for (int i = 0; i < n; i++) { |
| 75 | + int index = (k - 1) / factorial[i + 1]; |
| 76 | + chars[i] = (char) (numList.get(index) + '0'); |
| 77 | + numList.remove(index); |
| 78 | + k = k - factorial[i + 1] * index; |
| 79 | + } |
| 80 | + return new String(chars); |
| 81 | + } |
| 82 | +} |
0 commit comments