Leetcode 3543. Maximum Weighted K-Edge Path

  • [Leetcode 3543. Maximum Weighted K-Edge Path](#Leetcode 3543. Maximum Weighted K-Edge Path)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题思路上就是一个遍历的思路,我们只需要考察每一个节点作为起点时,所有长为 k k k的线段的长度,在符合条件的结果当中选出最大值即可。

需要注意的是,由于中间会有大量的重复操作存在,我们需要使用缓存来优化一下执行效率。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def maxWeight(self, n: int, edges: List[List[int]], k: int, t: int) -> int:
        graph = defaultdict(list)
        for u, v, w in edges:
            graph[u].append((v, w))

        @lru_cache(None)
        def dfs(u, k):
            if k == 0:
                return {0}
            if graph[u] == []:
                return set()
            ans = set()
            for v, w in graph[u]:
                nxt_set = dfs(v, k-1)
                for nxt in nxt_set:
                    if nxt + w < t:
                        ans.add(nxt+w)
            return ans
        
        return max(max(dfs(u, k)) if len(dfs(u, k)) > 0 else -1 for u in range(n))

提交代码评测得到:耗时216ms,占用内存48.2MB。

相关推荐
smj2302_796826521 天前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode
leoufung1 天前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
im_AMBER1 天前
Leetcode 59 二分搜索
数据结构·笔记·学习·算法·leetcode
leoufung1 天前
LeetCode 61. 旋转链表(Rotate List)题解与思路详解
leetcode·链表·list
leoufung1 天前
逆波兰表达式 LeetCode 题解及相关思路笔记
linux·笔记·leetcode
Aspect of twilight2 天前
LeetCode华为大模型岗刷题
python·leetcode·华为·力扣·算法题
2301_807997382 天前
代码随想录-day47
数据结构·c++·算法·leetcode
Elias不吃糖2 天前
LeetCode每日一练(3)
c++·算法·leetcode
小年糕是糕手2 天前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode
sheeta19982 天前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode