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。

相关推荐
琢磨先生David8 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝8 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll8 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐8 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶8 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER8 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了8 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333338 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录8 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1238 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode