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:

“123”
“132”
“213”
“231”
“312”
“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”

给出数字n和k,找出n!的排列组合中第k个排列组合

思路:
可以看到固定首位数字后,还剩下(n-1)个数,也就是说以每个数字开头的排列组合有(n-1)! 个,只需用(k-1)/(n-1)!+1就能确定首位数字,
确定首位数字后,用k % (n-1)! 得到子序列中index的k,
然后每个首位数字对应(n-2)!个组合,用(k-1)/(n-2)!+1确定第二位数字,
这样循环下去,
一共n个数字,首位对应后面的(n-1)!个组合,最后一位对应最后0!个组合,所以循环从(n-1)到0

而且可以看到比如“213”,确认首位2之后,下面要取“13”,“31”两个组合中的一个,比如确认是这个子序列中的第2个(k=2),这时首位数字要取3而不是2,所以可以看出每确定完一个数字,要把该数字从数字表中删除,避免重复利用

    public String getPermutation(int n, int k) {
        String result = "";
        int[] sum = new int[n];
        ArrayList<Integer> index = new ArrayList<>();
        
        Arrays.fill(sum, 1);
        index.add(1);
        
        for(int i = 1; i < n; i++) {
            sum[i] = sum[i-1] * i;
            index.add(i);
        }
        
        index.add(n);
        k --;
        
        for (int i = n-1; i >= 0; i--) {
            int num = k / sum[i] + 1;
            result += index.get(num);
            index.remove(num);
            k = k % sum[i];
        }
        
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值