diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/README.md" index d836612be9356..0c4335cc4fe29 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/README.md" @@ -189,6 +189,35 @@ func allPathsSourceTarget(graph [][]int) [][]int { } ``` +#### Swift + +```swift +class Solution { + private var results = [[Int]]() + private var graph = [[Int]]() + + func allPathsSourceTarget(_ graph: [[Int]]) -> [[Int]] { + self.graph = graph + var path = [0] + dfs(0, &path) + return results + } + + private func dfs(_ node: Int, _ path: inout [Int]) { + if node == graph.count - 1 { + results.append(Array(path)) + return + } + + for next in graph[node] { + path.append(next) + dfs(next, &path) + path.removeLast() + } + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/Solution.swift" new file mode 100644 index 0000000000000..687ea6eb06818 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/Solution.swift" @@ -0,0 +1,24 @@ +class Solution { + private var results = [[Int]]() + private var graph = [[Int]]() + + func allPathsSourceTarget(_ graph: [[Int]]) -> [[Int]] { + self.graph = graph + var path = [0] + dfs(0, &path) + return results + } + + private func dfs(_ node: Int, _ path: inout [Int]) { + if node == graph.count - 1 { + results.append(Array(path)) + return + } + + for next in graph[node] { + path.append(next) + dfs(next, &path) + path.removeLast() + } + } +}