LeetCode Algorithm 797. 所有可能的路径
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Algorithm 797. 所有可能的路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
797. 所有可能的路徑
Ideas
首先題目要求的所有可能的路徑,所以這是一個搜索問題,要搜索所有的狀態空間,所以應該用DFS。
我們從0節點出發,深入探索所有可能的下一步路線,直到到達 n - 1 節點或者達到一個曾經已經訪問過的節點。
Code
Python
from typing import List from copy import deepcopyclass Solution:def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:def dfs(node, path):if node == n - 1:ans.append(deepcopy(path + [node]))returnfor next_node in graph[node]:if next_node not in path:path.append(node)dfs(next_node, path)path.pop()n = len(graph)ans = []dfs(0, [])return ansif __name__ == '__main__':print(Solution().allPathsSourceTarget(graph=[[4, 3, 1], [3, 2, 4], [3], [4], []]))總結
以上是生活随笔為你收集整理的LeetCode Algorithm 797. 所有可能的路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hive SQL子句中 group by
- 下一篇: 2018年第九届蓝桥杯 - 省赛 - C