Leetcode 1443. Minimum Time to Collect All Apples in a Tree (python)

这篇博客主要探讨了LeetCode中的问题1443,即如何在树中以最小时间收集所有苹果。作者提供了两种Python解法,第一种利用深度优先搜索(DFS),在路径上找到所有被访问的边,计算所需时间。第二种DFS解法通过返回子树是否有苹果和访问时间来优化。在二刷过程中,作者强调了采用自底向上的思考方式对于解决这类树形问题的重要性,并给出了C++版本的解法和一种更高效的解法,该解法通过一个返回变量和hasApple数组管理成本。所有解法的时间复杂度为O(n),空间复杂度为O(n)。
摘要由CSDN通过智能技术生成

题目

在这里插入图片描述

解法1:

利用dfs,找出所有的在摘苹果的过程中会被访问的边。这些被访问的边数*2就是答案
这种做法需要保存当前路径,当发现当前路径包含苹果时,将这些边加入访问列表。这样做的坏处在于,每条边可能被加入多次,意味着时间复杂度的增加,事实证明这种做法确实不都快,刚刚过TLE的线。但利用字典或者set,还是可以不重复的记录摘苹果时需要被访问的边

class Solution:
    def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
        # main idea: find the edges has been used through dfs, the total time is the number of used_edges*2
        
        # dfs to visited every node
        def dfs(node,path):
            # append current node to path
            path.append(node)
            visited[node] = True
            # if current node has apple, we add the edges in the path from root to current node
            if hasApple[node]:
                for i in range(1,len(path)):
                    edge = (path[i-1],path[i])
                    used_edge[edge] = True
            for nei in graph[node]:
                if not visited[nei]:
                    dfs(nei,path[:])
                
                
        graph = collections.defaultdict(list)
        for i,edge in enumerate(edges):
            graph[edge[0]].append(edge[1])
            graph[edge[1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值