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;
                }
            }
        }
    } 
     
}

    
    


发布了52 篇原创文章 · 获赞 0 · 访问量 547

猜你喜欢

转载自blog.csdn.net/weixin_40300702/article/details/105396785