LeetCode LCP 07. 传递信息

Posted Alex_996

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode LCP 07. 传递信息相关的知识,希望对你有一定的参考价值。

题目链接:LCP 07. 传递信息

Ideas

算法:深度优先搜索
数据结构:图
思路:题目中要求的是所有的方案数,自然而然的想到要用深度优先搜索DFS,通过k来控制搜索的深度即可。

Code

Python

class Solution:
	def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
		def dfs(idx, depth):
			if depth > k:
				return
			if depth == k and idx == n - 1:
				nonlocal ans
				ans += 1
			for target in adjacency.get(idx, []):
				dfs(target, depth + 1)
		
		adjacency = 
		for (start, end) in relation:
			if adjacency.get(start, None):
				adjacency[start].append(end)
			else:
				adjacency[start] = [end]
		
		ans = 0
		dfs(0, 0)
		return ans

以上是关于LeetCode LCP 07. 传递信息的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode LCP 07. 传递信息

leetcode LCP.07 传递信息

leetcode LCP.07 传递信息

leetcode LCP 07. 传递信息

LeetCode LCP 07. 传递信息 / NC111 最大数 / NC16 判断二叉树是否对称 / NC13 二叉树的最大深度

文巾解题 LCP 07. 传递信息