leetcode------Permutation Sequence

标题:Permutation Sequence
通过率:22.7%
难度:中等

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.

本题就是求n个数全排列的第k个是什么,可以这样看

n个数的全排列个数是n!,第一个位置又n种可能,每种可能后的组合是(n-1)!

那么可以先求第一位数。k/(n-1)!,意思如下:

假如n=3,那么开头为1的有2种,2的有两种,3的有两种,如果是求第五个,

那么5/2=2,数组位置2刚好就是3,求完第一个后要把这个位置的前边的可能删除,即求k%fa,余数就是用来求第二位数字

,然后迭代去求,代码如下:

注意list第一位的位置也是0,所以要求的第k位,其实是求第k-1位

代码如下:

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         ArrayList<Integer> num=new ArrayList<Integer>();
 4         int fa=1;
 5         for(int i=1;i<=n;i++){
 6             num.add(i);
 7             fa*=i;
 8         }
 9         k-=1;
10         StringBuilder sb = new StringBuilder();
11         for(int i=n;i>0;i--){
12             fa=fa/i;
13             int index=k/fa;
14             sb.append(num.get(index));
15             num.remove(index);
16             k=k%fa;
17         }
18         return sb.toString();
19     }
20 }

 

转载于:https://www.cnblogs.com/pkuYang/p/4361269.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值