Leecode60 permutation-sequence

题目描述

集合[1,2,3,…,n]一共有n!种不同的排列
按字典序列出所有的排列并且给这些排列标上序号
我们就会得到以下的序列(以n=3为例)
“123”
“132”
“213”
“231”
“312”
“321”
现在给出n和k,请返回第k个排列
注意:n在1到9之间

分析

  • 这是一个排列问题,可以通过回溯法进行遍历。
  • 对序列进行计数。

java 代码

public class Solution {
    String res = "";
    int count = 0;
    public String getPermutation(int n, int k) {
       int num [] = new int [n];
        for(int i = 0;i < num.length; i++){
            num[i] =  i+1;
        }
        // num可用数据集,求第k个,从第0个位置填数,原始结果“”
        helper(num,k, 0, "");
        return res;
    }    
    public void helper(int num [],int k,int position,String s){
        if(position == num.length){
            count++;
            if(count == k){
                res = s + "";
            }            
        }else{
            for(int i = 0; i < num.length; i++){
                //没有使用过
                if(num[i] != 0){
                    int temp = num[i];
                    num[i] = 0;
                    helper(num,k,position+1,s+temp);
                    num[i] = temp;                    
                }                
                if(count == k){
                    break;
                }
            }
        }
    } 
     
}

    
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值