2024.4.11力扣每日一题——互质树

题目来源

力扣每日一题;题序:1766

我的题解

方法一 深度优先遍历+回溯+存储父节点

使用一个List存储深度优先遍历过程中的父节点,然后从List的右侧开始遍历,直到与当前节点互质结束。

时间复杂度:O( n 2 n^2 n2)
空间复杂度:O(n+h)。h是树的高度,表示递归栈的空间

//会超时
public int[] getCoprimes(int[] nums, int[][] edges) {
    int n=nums.length;
    List<Integer>[] g=createGraph(n,edges);
    int[] res=new int[n];
    res[0]=-1;
    List<Integer> l=new ArrayList<>();
    l.add(0);
    dfs(g,nums,l,res,0,-1);
    return res;
}
public void dfs(List<Integer>[] g,int[] nums,List<Integer> parent,int[] res,int cur,int pre){
    for(int next:g[cur]){
        if(next!=pre){
            res[next]=check(nums,next,parent);
            parent.add(next);
            dfs(g,nums,parent,res,next,cur);
            parent.remove(parent.size()-1);
        }
    }

}
//获取互质的第一个祖先节点
public int check(int[] nums,int cur,List<Integer> parent){
    int res=-1;
    for(int i=parent.size()-1;i>=0;i--){
        if(gcd(nums[cur],nums[parent.get(i)])==1){
            res=parent.get(i);
            break;
        }
    }
    return res;
}
public List<Integer>[] createGraph(int n,int[][] edges){
    List<Integer>[] g=new ArrayList[n];
    for(int i=0;i<n;i++)
        g[i]=new ArrayList<>();
    for(int[] t:edges){
        int from =  t[0];
        int to = t[1];
        g[from].add(to);
        g[to].add(from);
    }
    return g;
}
public int gcd(int x,int y){
    if(y==0)
        return x;
    return gcd(y,x%y);
}
方法二 官方深度优先遍历

没怎么看懂,自己看官方题解

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

相关推荐

  1. 2024.4.11每日——

    2024-04-14 04:04:01       15 阅读
  2. 每日145二叉的后序遍历

    2024-04-14 04:04:01       38 阅读
  3. 每日144二叉的前序遍历

    2024-04-14 04:04:01       35 阅读
  4. 每日987二叉的垂序遍历

    2024-04-14 04:04:01       35 阅读
  5. 每日590N叉的后序遍历

    2024-04-14 04:04:01       25 阅读
  6. 每日:课程表Ⅱ

    2024-04-14 04:04:01       44 阅读
  7. 每日 6/6

    2024-04-14 04:04:01       11 阅读
  8. 每日 6/7

    2024-04-14 04:04:01       7 阅读
  9. 每日 6/5

    2024-04-14 04:04:01       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-14 04:04:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-14 04:04:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-14 04:04:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-14 04:04:01       18 阅读

热门阅读

  1. C语言题目:成绩归类

    2024-04-14 04:04:01       36 阅读
  2. Vector部分底层源码解析

    2024-04-14 04:04:01       20 阅读
  3. Vue 打包或运行时报错Error: error:0308010C

    2024-04-14 04:04:01       53 阅读
  4. RTK高精度定位

    2024-04-14 04:04:01       15 阅读
  5. LeetCode 139. 单词拆分

    2024-04-14 04:04:01       14 阅读
  6. 人工智能技术的创业机遇

    2024-04-14 04:04:01       14 阅读
  7. [ LeetCode ] 题刷刷(Python)-第49题:字母异位词分组

    2024-04-14 04:04:01       14 阅读
  8. 如何在Python中实现设计模式?

    2024-04-14 04:04:01       16 阅读
  9. C动\静态库编译

    2024-04-14 04:04:01       14 阅读
  10. python3面向对象

    2024-04-14 04:04:01       14 阅读
  11. pyqt写个星三角降压启动方式2

    2024-04-14 04:04:01       13 阅读