[leetcode] Permutation Sequence

本文介绍了一种高效算法,用于找出由1至n组成的第k个全排列。通过递归分解问题规模,利用阶乘计算定位每一位上的数字,避免了传统生成所有排列再选取的方法。

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.

Note: Given n will be between 1 and 9 inclusive.

 

Solution:

计算 1~n 数字的第k个排列

思路1:从小到大生成同时计数,直到第k个。 肯定超时试都不用试。。

思路2:直接根据规律计算第k个排列。

分析:1~n个数共有n!个排列,1开头的有(n-1)!个,2开头的(n-1)!个,...n开头的有(n-1)!个。因此用k/(n-1)!就确定了第一位数字,然后依次类推(用过的数字要去除),继续在(n-1)!个数中找第k%(n-1)!个数。

 

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         String s_n = generateString(n);
 4         int total = factorial(n);
 5         if(n==1 && k==1)
 6             return "1";
 7 
 8         char[] result = new char[n];
 9 
10         for (int i = 0; i < n; ++i) {
11             total /= (n - i);
12             int index = (k - 1) / total;
13             result[i] = s_n.charAt(index);
14             
15             s_n=s_n.replace(result[i]+"", "");
16             k-=index*total;
17         }
18 
19         return new String(result);
20     }
21 
22     private String generateString(int n) {
23         // TODO Auto-generated method stub
24         String sb = "";
25         for (int i = 1; i <= n; ++i) {
26             sb += i + "";
27         }
28         return sb;
29     }
30 
31     private int factorial(int n) {
32         // TODO Auto-generated method stub
33         int total = 1;
34         for (int i = 1; i <= n; i++)
35             total *= i;
36         return total;
37     }
38 }

 

转载于:https://www.cnblogs.com/Phoebe815/p/3997590.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值