Leetcode之Permutation Sequence(Permutation 专题)

专题:Permutation

原题:

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.

» Solve this problem


方法:

1. 建一个数组存阶乘,另一个数组存访问过的节点

2. 从n-1到0简历for-loop,其中建一个while-loop, 如果k大于对应正在遍历的i的阶乘,把k减小i的阶乘

3. 减小k的同时,增加tmp的值,这个while-loop结束条件是k小于i的对应阶乘

4. 接下来,简历一个for-loop,从0到n-1, 如果当前值小于对应的tmp,并且已被访问过,那么tmp继续加一

5. 把tmp的值加到stringbuilder后面,标记tmp对应的位数为已访问,进入下一轮大循环


代码:

public class Solution {
    public String getPermutation(int n, int k) {
        // Start typing your Java solution below
        // DO NOT write main() function
        boolean[] visited = new boolean[n];
        int[] factor = new int[n];
        factor[0] = 1;
        for(int i=1; i<n; i++)
            factor[i] = factor[i-1]*i;
        StringBuilder sb = new StringBuilder();
            
        for(int i=n-1; i>=0; i--){
            int tmp = 1;
            while(k > factor[i]){
                tmp++;
                k -= factor[i];
            }
            for(int j=0; j<n; j++)
                if(j+1<=tmp && visited[j])
                    tmp++;
            sb.append(tmp);
            visited[tmp-1] = true;
        }
        
        return sb.toString();
    }
}

小结:

这题运用了Permutation的标志性结构:boolean[] visited,当全局考虑时,布尔数组对于已访问的记录是必须的。和Next Permutation一样,结构不复杂,方法有点绕,不易理解。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值