[leetcode]60. Permutation Sequence排列序列

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"

题意

1~n有n!个排列,找出其中字典序排第k的排列。

思路

这是一道很数学的题, 没有什么fancy的算法,就得死命去找规律

code

 1  public String getPermutation(int n, int k) {
 2         char[] result = new char[n];
 3         List<Integer> list = new ArrayList<>();
 4         int[] factorial = new int[n];
 5 
 6         factorial[0] = 1;
 7         for (int i = 1; i < n; i++) {
 8             factorial[i] = factorial[i-1] *i;
 9         }
10         // factorial: 1, 1, 2
11         // 表示n对应全排列的个数和
12 
13         for (int i = 1; i <=n ; i++) {
14             list.add(i);
15         }
16         // 可用数字为 1-2-3, 用list的原因是稍后便于删除已用数字
17 
18         k--; //挑出一个高位数
19         // 开始从最高位到最后一位来生成结果
20         for (int i = 0; i < n ; i++) {
21             result[i] = Character.forDigit(list.remove(k/factorial[n-1-i]), 10);
22             k = k % factorial[n-1-i];
23         }
24         return new String(result);
25     }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/10953063.html
今日推荐