mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加 070爬楼梯 Java 版本
This commit is contained in:
@ -213,6 +213,28 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 常规方式
|
||||||
|
public int climbStairs(int n) {
|
||||||
|
int[] dp = new int[n + 1];
|
||||||
|
dp[0] = 1;
|
||||||
|
dp[1] = 1;
|
||||||
|
for (int i = 2; i <= n; i++) {
|
||||||
|
dp[i] = dp[i - 1] + dp[i - 2];
|
||||||
|
}
|
||||||
|
return dp[n];
|
||||||
|
}
|
||||||
|
// 用变量记录代替数组
|
||||||
|
public int climbStairs(int n) {
|
||||||
|
int a = 0, b = 1, c = 0; // 默认需要1次
|
||||||
|
for (int i = 1; i <= n; i++) {
|
||||||
|
c = a + b; // f(i - 1) + f(n - 2)
|
||||||
|
a = b; // 记录上一轮的值
|
||||||
|
b = c; // 向后步进1个数
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user