力扣题:LCP 07. 传递信息

https://leetcode-cn.com/problems/chuan-di-xin-xi/

反向回溯

1、反向回溯,可以节省时间,进行到哪一步没有连接可以直接结束返回0
2、创建字典dic,遍历relation,将每个点的值作为key,将能够连接到某个点的所有点组成列表作为value
3、回溯开始,初始值即为old = [n-1], 回溯有可能连接到这个点的所有点作为列表new
4、如果再某一次回溯时即old为空,则说明根本无法到达现在的点,直接输出0
5、如果old不为空,则遍历old中每一个元素为key,将字典中的value全部加入new,下一次回溯再把new赋值给old
6、遍历结束,只要输出最终的new列表中0的个数即可

`class Solution:
def numWays(self, n: int, relation: List[List[int]], k: int) -> int:

    dic = {}
    for L in relation:
        if L[1] in dic:
            dic[L[1]].append(L[0])
        else:
            dic[L[1]] = [L[0]]
    old = [n-1]
    for i in range(k):
        new = []
        if not old:
            return 0
        else:
            for j in old:
                if j in dic:
                    new += dic[j]
                old = new
    else:
        return new.count(0)

`

posted @ 2020-09-04 10:47  hisweetyGirl  阅读(136)  评论(0编辑  收藏  举报