【Leetcode每日一题】797. 所有可能的路径



题目

给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序

二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。

译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a 。

示例

示例1

输入: graph = [[1,2],[3],[3],[]]
输出: [[0,1,3],[0,2,3]]
解释: 有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3

示例2

输入: graph = [[4,3,1],[3,2,4],[3],[4],[]]
输出: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]

示例3

输入: graph = [[1],[]]
输出: [[0,1]]

示例4

输入: graph = [[1,2,3],[2],[3],[]]
输出: [[0,1,2,3],[0,2,3],[0,3]]

示例5

输入: graph = [[1,3],[2],[3],[]]
输出: [[0,1,2,3],[0,3]]


关键思路

使用动态规划的方法。

需要注意的是,本题为找到所有可能的路径,而非找到单一路径,所以我设计的动态规划表,维护了所有经过起点的路线,以方便更新和查找。


代码实现

class Solution(object):
    def allPathsSourceTarget(self, graph):
        """
        :type graph: List[List[int]]
        :rtype: List[List[int]]
        """

        dp = [ [0] ]  # set a dp table

        for i in range(len(graph)):  # number of nodes
            for path in dp:  # check the end of the current path
                if path[-1] == i:
                    for suf in graph[i]:
                        dp.append(path+[suf])
        
        return [ p for p in dp if p[-1] == len(graph)-1 ]


if __name__ == "__main__":
    graph = input()
    obj = Solution()
    result = obj.allPathsSourceTarget(graph)
    print(result)

运行结果

[[0, 1, 3],[0, 2, 3]]
[[0, 4], [0, 1, 4], [0, 3, 4], [0, 1, 3, 4], [0, 1, 2, 3, 4]]
[[0, 1]]
[[0, 3], [0, 2, 3], [0, 1, 2, 3]]
[[0, 3], [0, 1, 2, 3]]

链接

https://leetcode-cn.com/problems/all-paths-from-source-to-target

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值