题解 | #第K个n的排列#

第K个n的排列

http://www.nowcoder.com/practice/1595969179464e4c940a90b36abb3c54

import java.util.*;


public class Solution {
    
    public int n = 0;
    public int k = 0;
    public ArrayList<ArrayList<Integer>> res = new ArrayList<>();

    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param n int整型
     * @param k int整型
     * @return string字符串
     */
    public String KthPermutation(int n, int k) {
        // write code here
        this.n = n;
        this.k = k;
        ArrayList<Integer> nums = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            nums.add(i);
        }
        ArrayList<Integer> currentArr = new ArrayList<>();
        process(nums, currentArr);
        StringBuffer sb = new StringBuffer("");
        for (int num : res.get(k - 1)) {
            sb.append(num);
        }
        return new String(sb);
    }

    public void process(ArrayList<Integer> nums, ArrayList<Integer> currentArr) {
        if (currentArr.size() == n) {
            ArrayList<Integer> copyArr = new ArrayList<>();
            copyArr.addAll(currentArr);
            res.add(copyArr);
            return;
        }
        for (int i = 0; i < nums.size(); i++) {
            ArrayList<Integer> copyArr = new ArrayList<>();
            copyArr.addAll(nums);
            copyArr.remove(i);
            currentArr.add(nums.get(i));
            process(copyArr, currentArr);
            currentArr.remove(currentArr.size() - 1);
        }
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务