输出前n个数组合成的第k个数

本文介绍了一种算法,用于找出由1到n组成的n!个不同排列中的第k个排列序列。通过深度优先搜索(DFS)递归地构建排列序列,并使用辅助数组追踪已使用的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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):

"123"
"132"
"213"
"231"
"312"
"321" 

Given n and k, return the k th permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
用book数组指示当前还有哪些数字没有被放到数组arr里面,在修改并输出最后结果之后还要将它改回原来数组的样子。

public class Solution {
    static int k;
    static String s="";
    public String getPermutation(int n, int m) {
        k=m;
        dfs(n);
        return s;
    }

   public static void dfs(int n){  
        int[] arr = new int[n];  
        int[] book = new int[n];  
        dfs(0,arr,book);  
    }

    private static void dfs(int step, int[] arr, int[] book){  
        if(step==arr.length){ 
            if(k==1){
             s="";
            for(int i=0; i<arr.length; i++){  
                s=s+arr[i];
            }
            }
            k--;
            return;  
        }  
        for(int i=0; i<arr.length; i++){  
            if(book[i]==0){  
                arr[step]=i+1;  
                book[i] = 1;  
                dfs(step+1,arr,book);  
                book[i] = 0;  
            }  
        }  
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值