信息发布→ 登录 注册 退出

剑指Offer之Java算法习题精讲排列与N叉树

发布时间:2026-01-11

点击量:

题目一

 解法

class Solution {
    LinkedList<List<Integer>> ans = new LinkedList<List<Integer>>();
    public List<List<Integer>> permute(int[] nums) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        boolean[] bo = new boolean[nums.length];
        method(nums,bo,list);
        return ans;
    }
    public void method(int[] nums,boolean[] bo ,LinkedList<Integer> list){
        if(list.size()==nums.length){
            ans.add(new LinkedList(list));
            return;
        }
        for(int i = 0;i<nums.length;i++){
            if(bo[i]){
                continue;
            }
            list.add(nums[i]);
            bo[i] = true;
            method(nums,bo,list);
            list.removeLast();
            bo[i] = false;
        }
    }
}

题目二

 解法

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;
    public Node() {}
    public Node(int _val) {
        val = _val;
    }
    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
 
class Solution {
    public int maxDepth(Node root) {
        if(root==null){
            return 0;
        }
        int maxChildDepth = 0;
        for(int i = 0;i<root.children.size();i++){
            int childDepth = maxDepth(root.children.get(i));
            maxChildDepth = Math.max(maxChildDepth, childDepth);
        }
        return maxChildDepth+1;
    }
}
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!