diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index c92c581c..30c3642f 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -401,6 +401,38 @@ int climbStairs(int n){ } ``` +### Scala + +```scala +object Solution { + def climbStairs(n: Int): Int = { + if (n <= 2) return n + var dp = new Array[Int](n + 1) + dp(1) = 1 + dp(2) = 2 + for (i <- 3 to n) { + dp(i) = dp(i - 1) + dp(i - 2) + } + dp(n) + } +} +``` + +优化空间复杂度: +```scala +object Solution { + def climbStairs(n: Int): Int = { + if (n <= 2) return n + var (a, b) = (1, 2) + for (i <- 3 to n) { + var tmp = a + b + a = b + b = tmp + } + b // 最终返回b + } +} +``` -----------------------
diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index 785d0125..0b53e698 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -263,7 +263,7 @@ var fib = function(n) { }; ``` -TypeScript +### TypeScript ```typescript function fib(n: number): number { @@ -342,5 +342,33 @@ pub fn fib(n: i32) -> i32 { return fib(n - 1) + fib(n - 2); } ``` + +### Scala + +动态规划: +```scala +object Solution { + def fib(n: Int): Int = { + if (n <= 1) return n + var dp = new Array[Int](n + 1) + dp(1) = 1 + for (i <- 2 to n) { + dp(i) = dp(i - 1) + dp(i - 2) + } + dp(n) + } +} +``` + +递归: +```scala +object Solution { + def fib(n: Int): Int = { + if (n <= 1) return n + fib(n - 1) + fib(n - 2) + } +} +``` + -----------------------
diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 0006f7ac..92fb2920 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -323,5 +323,35 @@ int minCostClimbingStairs(int* cost, int costSize){ return dp[i-1] < dp[i-2] ? dp[i-1] : dp[i-2]; } ``` + +### Scala + +```scala +object Solution { + def minCostClimbingStairs(cost: Array[Int]): Int = { + var dp = new Array[Int](cost.length) + dp(0) = cost(0) + dp(1) = cost(1) + for (i <- 2 until cost.length) { + dp(i) = math.min(dp(i - 1), dp(i - 2)) + cost(i) + } + math.min(dp(cost.length - 1), dp(cost.length - 2)) + } +} +``` + +第二种思路: dp[i] 表示爬到第i-1层所需的最小花费,状态转移方程为: dp[i] = min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]) +```scala +object Solution { + def minCostClimbingStairs(cost: Array[Int]): Int = { + var dp = new Array[Int](cost.length + 1) + for (i <- 2 until cost.length + 1) { + dp(i) = math.min(dp(i - 1) + cost(i - 1), dp(i - 2) + cost(i - 2)) + } + dp(cost.length) + } +} +``` + -----------------------