LeetCode 1766.互质树:设计(深度优先搜索)

【LetMeFly】1766.互质树:设计(深度优先搜索)

力扣题目链接:https://leetcode.cn/problems/tree-of-coprimes/

给你一个 n 个节点的树(也就是一个无环连通无向图),节点编号从 0n - 1 ,且恰好有 n - 1 条边,每个节点有一个值。树的 根节点 为 0 号点。

给你一个整数数组 nums 和一个二维数组 edges 来表示这棵树。nums[i] 表示第 i 个点的值,edges[j] = [u~j~, v~j~] 表示节点 u~j~ 和节点 v~j~ 在树中有一条边。

gcd(x, y) == 1 ,我们称两个数 xy互质的 ,其中 gcd(x, y)xy最大公约数

从节点 i 最短路径上的点都是节点 i 的祖先节点。一个节点 不是 它自己的祖先节点。

请你返回一个大小为 n 的数组 ans ,其中ans[i]是离节点 i 最近的祖先节点且满足nums[i]nums[ans[i]]互质的 ,如果不存在这样的祖先节点,ans[i]-1

示例 1:

复制代码
输入:nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]
输出:[-1,0,0,1]
解释:上图中,每个节点的值在括号中表示。
- 节点 0 没有互质祖先。
- 节点 1 只有一个祖先节点 0 。它们的值是互质的(gcd(2,3) == 1)。
- 节点 2 有两个祖先节点,分别是节点 1 和节点 0 。节点 1 的值与它的值不是互质的(gcd(3,3) == 3)但节点 0 的值是互质的(gcd(2,3) == 1),所以节点 0 是最近的符合要求的祖先节点。
- 节点 3 有两个祖先节点,分别是节点 1 和节点 0 。它与节点 1 互质(gcd(3,2) == 1),所以节点 1 是离它最近的符合要求的祖先节点。

示例 2:

复制代码
输入:nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
输出:[-1,0,-1,0,0,0,-1]

提示:

  • nums.length == n
  • 1 <= nums[i] <= 50
  • 1 <= n <= 10^5^
  • edges.length == n - 1
  • edges[j].length == 2
  • 0 <= u~j~, v~j~ < n
  • u~j~ != v~j~

解题方法:设计(深度优先搜索)

这道题的数据范围中可以得知, n u m s [ i ] nums[i] nums[i]最大只有 50 50 50。因此可以建立一下数据结构:

  • [[int]] gcds; // gcds[i]: 和i互质的所有数(题目范围内)
  • [[int]] path; // path: dfs到当前节点时所有的祖先节点 | path[i]: 值为i的祖先节点们
  • [int] num2depth; // num2depth[i]: 节点i的深度(默认值为0)
  • [[int]] graph; // graph[i]: 节点i的所有相邻节点
  • [int] ans; // ans: 最终要返回的答案

其中 g c d s gcds gcds可以在预处理时计算得出 1 1 1到 50 50 50的范围内每个数的所有质因数。

而 g r a p h graph graph课可以通过遍历一遍 e d g e s edges edges数组而得到。

至于 p a t h path path和 d e p t h depth depth,则可以在深度优先搜索的同时得到:

cpp 复制代码
void dfs(nums, num, depth) {
    num2depth[num] = depth;
    int thisVal = nums[num];
    ...  // 依据gcds[thisVal]遍历path中互质的数,深度最深的那个即为答案
    path[thisVal].push_back(num);
    ...  // 遍历graph开始递归
    path[thisVal].pop_back();
}
  • 时间复杂度 O ( C 2 + C n ) O(C^2+Cn) O(C2+Cn),其中 C C C为每个节点的数据范围,本题中 C = 50 C=50 C=50
  • 空间复杂度 O ( C 2 + n ) O(C^2+n) O(C2+n)

AC代码

C++
cpp 复制代码
class Solution {
private:
    vector<vector<int>> gcds;   // gcds[i]: 和i互质的所有数(题目范围内)
    vector<vector<int>> path;   // path: dfs到当前节点时所有的祖先节点 | path[i]: 值为i的祖先节点们
    vector<int> num2depth;      // num2depth[i]: 节点i的深度(默认值为0)
    vector<vector<int>> graph;  // graph[i]: 节点i的所有相邻节点
    vector<int> ans;            // ans: 最终要返回的答案

    void initGcds() {
        gcds.resize(51);
        for (int i = 1; i <= 50; i++) {
            for (int j = 1; j <= 50; j++) {
                if (__gcd(i, j) == 1) {
                    gcds[i].push_back(j);
                    gcds[j].push_back(i);
                }
            }
        }
    }

    void initPath() {
        path.resize(51);
    }

    void initNum2depth(vector<int>& nums) {
        num2depth.resize(nums.size());
    }

    void initGraph(vector<int>& nums, vector<vector<int>>& edges) {
        graph.resize(nums.size());
        for (vector<int>& edge : edges) {
            graph[edge[0]].push_back(edge[1]);
            graph[edge[1]].push_back(edge[0]);
        }
    }

    void initAns(vector<int>& nums) {
        ans = vector<int>(nums.size(), -1);
    }

    void dfs(vector<int>& nums, int num, int depth) {
        num2depth[num] = depth;
        for (int coprime : gcds[nums[num]]) {
            if (path[coprime].size()) {
                int lastNum = path[coprime].back();
                if (ans[num] == -1 || num2depth[lastNum] > num2depth[ans[num]]) {
                    ans[num] = lastNum;
                }
            }
        }
        path[nums[num]].push_back(num);
        for (int nextNum : graph[num]) {
            if (!num2depth[nextNum]) {
                dfs(nums, nextNum, depth + 1);
            }
        }
        path[nums[num]].pop_back();
    }
public:
    vector<int> getCoprimes(vector<int>& nums, vector<vector<int>>& edges) {
        initGcds();
        initPath();
        initNum2depth(nums);
        initGraph(nums, edges);
        initAns(nums);
        dfs(nums, 0, 1);  // 根节点视为1层,和默认值不同
        return ans;
    }
};

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/137641344

相关推荐
爱上语文3 小时前
Java LeetCode每日一题
java·开发语言·leetcode
大二转专业8 小时前
408算法题leetcode--第24天
考研·算法·leetcode
__AtYou__14 小时前
Golang | Leetcode Golang题解之第448题找到所有数组中消失的数字
leetcode·golang·题解
LluckyYH15 小时前
代码随想录Day 58|拓扑排序、dijkstra算法精讲,题目:软件构建、参加科学大会
算法·深度优先·动态规划·软件构建·图论·dfs
转调15 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
huanxiangcoco16 小时前
152. 乘积最大子数组
python·leetcode
希望有朝一日能如愿以偿17 小时前
力扣题解(飞机座位分配概率)
算法·leetcode·职场和发展
Espresso Macchiato17 小时前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417
数据分析螺丝钉19 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
￴ㅤ￴￴ㅤ9527超级帅19 小时前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵