LeetCode 笔记21 生成第k个排列

本文介绍了一种通过数学方法快速找到集合[1,2,3,...,n]中第k个字典序排列的方法。利用(n-1)!的特性确定每个位置上的数值,通过递减block大小来解决子问题。

题目是这样的:

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 (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

 

Given n and k, return the kth permutation sequence.

就是说,按字典序给出第k个排列。

因为之前做了“生成下一个排列”的题目,就直接拿过来用了。不料超时,于是只能用数学的方法做了。当然这也不是我想出来的,而是搜出来的(逃。。。)

基本的想法是,对于第k个排列,{a1, a2, a3, ..., an}, a1 是多少呢?

因为{a2, a3, ..., an} 一共有 (n-1)!种,a1在num中的index相当于 k / (n-1)!。换句话解释,就是一共有n个block,每个block大小是(n-1)!这么大,现在要求的就是在哪个block。

同理,求a2的时候,a1(在哪个block)已经求出来了,update k = k % (n-1)!, block的大小变成了(n-2)!, 这又是一个子问题了。

代码如下:

 1 public String getPermutation(int n, int k) {
 2         int[] num = new int[n];
 3         int perNumCount = 1;
 4 
 5         for(int i = 0; i < n; i++) {
 6             num[i] = i+1;
 7             perNumCount *= i + 1;
 8         }
 9         k--;
10         StringBuilder sb = new StringBuilder();
11         for(int i = 0; i < n; i++) {
12             perNumCount = perNumCount / (n - i);
13             int choosed = k / perNumCount;
14             sb.append(String.valueOf(num[choosed]));
15             for(int j = choosed; j < n - i - 1; j++) {
16                 num[j] = num[j+1]; 
17             }
18             k = k % perNumCount;
19         }
20         return sb.toString();
21     }

 

转载于:https://www.cnblogs.com/lichen782/p/4265258.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值