题目:力扣

解题思路:

可以看注释

class Solution {
    StringBuffer sb = new StringBuffer();
    List<Integer> choice = new LinkedList<>();
    public String getPermutation(int n, int k) {
        //先把所有的元素加入到选择列表中
        for(int i = 1; i <= n; i++){
            choice.add(i);
        }
        return helper(choice, k);

    }
    //choice表示选择,按大小顺序排列,k表示取第k个序列,从1开始计数
    public String helper(List<Integer> choice, int k){
        //如果选择为空,或者序列数为0,返空字符串
        if(choice.size() == 0 || k == 0){
            return "";
        }
        //以某一元素开头的序列个数,一共有n!/n个
        int nums_of_each = jie(choice.size());
        //第k个序列以第几个元素开头
        int which_one = k/nums_of_each;
        //确定第一个元素后,再确定是以某元素开头的第几个
        int order = k%nums_of_each;
        //如果取余不等于0,表示开头元素是which_one的下一个
        if(order != 0){
            which_one = which_one+1;
        }
        //如果等于0,表示是which_one开头的最后一个
        else{
            order = nums_of_each;
        }
        //加入开头元素
        sb.append(choice.get(which_one-1));
        //从选择中去除该开头元素
        choice.remove(which_one-1);
        //找第二个元素
        helper(choice, order);
        return sb.toString();
    }
    
    //每个元素开头的个数
    public int jie(int n){
        int res = 1;
        for(int i = 1; i < n; i++){
            res = res*i;
        }
        return res;
    }
}