From ce475df9789cf3bc968929cadb3a1422728ed1d4 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Wed, 30 Oct 2024 08:30:27 +0100 Subject: [PATCH] feat: add swift implementation to lcof2 problem: No.110 --- .../README.md" | 29 +++++++++++++++++++ .../Solution.swift" | 24 +++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 "lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/Solution.swift" 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() + } + } +}