题解 | #第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);
        }
    }
}
全部评论

相关推荐

看到这个内容真是闹麻了。。。。。。现在有了AI以后很多人面试都会作弊吗?&nbsp;那对老老实实面试的人岂不是不公平....
程序员牛肉:公平那是对小孩子讲的童话故事,成年人的世界只有能不能接受失败的后果。 你要是能接受面试作弊被发现之后多家公司联合永久拉黑的后果,你就搞。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务