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"

 

解法:按照k的位置一步步缩小处理范围,可以使用迭代也可以使用递归。这里使用了迭代的方法。

举个例子:比如说输入是4,9.

先看第一位要取什么,知道k=9,那我把 4!/4 知道每个槽位放六个数,故第一位必然是“2”。以此类推就行。

本题我觉得难点是在于list的操作,需要一个数据结构保存1到n,取出相应数字之后还能有序。这里使用了ArrayList。

还有一个位数ins时,需要用(k-1)/cnt,这里需要认真理解下,因为槽位内也是从0开始index,所有需要减一。

class Solution {
    public String getPermutation(int n, int k) {
        int cnt = 1;//阶乘的结果
        List<Integer> ts = new ArrayList<Integer>();//数字集,自动排序
        for(int i=1;i<=n;i++){
            cnt = cnt * i;
            ts.add(i);
        }
        
        //判断k是否大于阶乘/n,缩减范围
        //需要一个数据结构保存1到n,并且支持取出相应的数字之后还能有序
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<n;i++){
            cnt = cnt/(n-i);
            if(k>=0){   //0也是index
                int ins = (k-1)/cnt; //why?类比为一个槽位内也是index从0开始的
                k = k-ins*cnt;
                sb.append(ts.get(ins));
                ts.remove(ts.get(ins));
            }
        }
        return sb.toString();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值