[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     }

 

转载于:https://www.cnblogs.com/liuliu5151/p/10953063.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值