diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index aa7c8ab8..5790df69 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -436,5 +436,21 @@ int uniquePaths(int m, int n){ } ``` +### Scala + +```scala +object Solution { + def uniquePaths(m: Int, n: Int): Int = { + var dp = Array.ofDim[Int](m, n) + for (i <- 0 until m) dp(i)(0) = 1 + for (j <- 1 until n) dp(0)(j) = 1 + for (i <- 1 until m; j <- 1 until n) { + dp(i)(j) = dp(i - 1)(j) + dp(i)(j - 1) + } + dp(m - 1)(n - 1) + } +} +``` + -----------------------
diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index e3857db6..c7326b63 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -476,5 +476,37 @@ int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridSize, int* obst } ``` +### Scala + +```scala +object Solution { + import scala.util.control.Breaks._ + def uniquePathsWithObstacles(obstacleGrid: Array[Array[Int]]): Int = { + var (m, n) = (obstacleGrid.length, obstacleGrid(0).length) + var dp = Array.ofDim[Int](m, n) + + // 比如break、continue这些流程控制需要使用breakable + breakable( + for (i <- 0 until m) { + if (obstacleGrid(i)(0) != 1) dp(i)(0) = 1 + else break() + } + ) + breakable( + for (j <- 0 until n) { + if (obstacleGrid(0)(j) != 1) dp(0)(j) = 1 + else break() + } + ) + + for (i <- 1 until m; j <- 1 until n; if obstacleGrid(i)(j) != 1) { + dp(i)(j) = dp(i - 1)(j) + dp(i)(j - 1) + } + + dp(m - 1)(n - 1) + } +} +``` + -----------------------