|
| 1 | +import Foundation |
| 2 | + |
| 3 | +// Straight forward DFS. Time limit exceeded |
| 4 | +// Time: O(2^(m*n)) |
| 5 | +class Solution { |
| 6 | + func uniquePaths(_ m: Int, _ n: Int) -> Int { |
| 7 | + return uniquePathHelper((m, n), (0,0)) |
| 8 | + } |
| 9 | + |
| 10 | + func uniquePathHelper(_ destinationCoord: (Int, Int), _ currentCoord: (Int, Int)) -> Int { |
| 11 | + if currentCoord == (destinationCoord.0 - 1, destinationCoord.1 - 1) { |
| 12 | + return 1 |
| 13 | + } |
| 14 | + if currentCoord.0 >= destinationCoord.0 || currentCoord.1 >= destinationCoord.1 { |
| 15 | + return 0 |
| 16 | + } |
| 17 | + |
| 18 | + let right = uniquePathHelper(destinationCoord, (currentCoord.0 + 1, currentCoord.1)) |
| 19 | + let down = uniquePathHelper(destinationCoord, (currentCoord.0, currentCoord.1 + 1)) |
| 20 | + return right + down |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +// Top-Down with memoizations. Accepted |
| 26 | +// Time: O(2^(m*n)) |
| 27 | +class Solution { |
| 28 | + func uniquePaths(_ m: Int, _ n: Int) -> Int { |
| 29 | + var memo = [String:Int]() |
| 30 | + return uniquePathHelper((m, n), (0,0), &memo) |
| 31 | + } |
| 32 | + |
| 33 | + func uniquePathHelper(_ destinationCoord: (Int, Int), _ currentCoord: (Int, Int), _ memo: inout [String:Int]) -> Int { |
| 34 | + if let value = memo["\(currentCoord.0)-\(currentCoord.1)"] { |
| 35 | + return value |
| 36 | + } |
| 37 | + if currentCoord == (destinationCoord.0 - 1, destinationCoord.1 - 1) { |
| 38 | + return 1 |
| 39 | + } |
| 40 | + if currentCoord.0 >= destinationCoord.0 || currentCoord.1 >= destinationCoord.1 { |
| 41 | + return 0 |
| 42 | + } |
| 43 | + |
| 44 | + let right = uniquePathHelper(destinationCoord, (currentCoord.0 + 1, currentCoord.1), &memo) |
| 45 | + let down = uniquePathHelper(destinationCoord, (currentCoord.0, currentCoord.1 + 1), &memo) |
| 46 | + memo["\(currentCoord.0)-\(currentCoord.1)"] = right + down |
| 47 | + return right + down |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | + |
| 52 | +// Bottom-Up dp. Accepted |
| 53 | +// Time: O(m*n) |
| 54 | +class Solution { |
| 55 | + func uniquePaths(_ m: Int, _ n: Int) -> Int { |
| 56 | + var dpTable = Array(repeating: Array(repeating: 1, count: m), count: n) |
| 57 | + for i in 1..<n { |
| 58 | + for j in 1..<m { |
| 59 | + dpTable[i][j] = dpTable[i - 1][j] + dpTable[i][j - 1] |
| 60 | + } |
| 61 | + } |
| 62 | + return dpTable[n - 1][m - 1] |
| 63 | + } |
| 64 | +} |
0 commit comments