mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1760 from codeSu97/master
feat: 0070.爬楼梯.md 增加 rust代码
This commit is contained in:
@ -28,7 +28,7 @@
|
|||||||
* 1 阶 + 2 阶
|
* 1 阶 + 2 阶
|
||||||
* 2 阶 + 1 阶
|
* 2 阶 + 1 阶
|
||||||
|
|
||||||
# 视频讲解
|
# 视频讲解
|
||||||
|
|
||||||
**《代码随想录》算法视频公开课:[带你学透动态规划-爬楼梯|LeetCode:70.爬楼梯)](https://www.bilibili.com/video/BV17h411h7UH),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
|
**《代码随想录》算法视频公开课:[带你学透动态规划-爬楼梯|LeetCode:70.爬楼梯)](https://www.bilibili.com/video/BV17h411h7UH),相信结合视频在看本篇题解,更有助于大家对本题的理解**。
|
||||||
|
|
||||||
@ -216,7 +216,7 @@ public:
|
|||||||
## 其他语言版本
|
## 其他语言版本
|
||||||
|
|
||||||
|
|
||||||
### Java
|
### Java
|
||||||
|
|
||||||
```java
|
```java
|
||||||
// 常规方式
|
// 常规方式
|
||||||
@ -237,7 +237,7 @@ class Solution {
|
|||||||
public int climbStairs(int n) {
|
public int climbStairs(int n) {
|
||||||
if(n <= 2) return n;
|
if(n <= 2) return n;
|
||||||
int a = 1, b = 2, sum = 0;
|
int a = 1, b = 2, sum = 0;
|
||||||
|
|
||||||
for(int i = 3; i <= n; i++){
|
for(int i = 3; i <= n; i++){
|
||||||
sum = a + b; // f(i - 1) + f(i - 2)
|
sum = a + b; // f(i - 1) + f(i - 2)
|
||||||
a = b; // 记录f(i - 1),即下一轮的f(i - 2)
|
a = b; // 记录f(i - 1),即下一轮的f(i - 2)
|
||||||
@ -261,7 +261,7 @@ class Solution:
|
|||||||
for i in range(2,n+1):
|
for i in range(2,n+1):
|
||||||
dp[i]=dp[i-1]+dp[i-2]
|
dp[i]=dp[i-1]+dp[i-2]
|
||||||
return dp[n]
|
return dp[n]
|
||||||
|
|
||||||
# 空间复杂度为O(1)版本
|
# 空间复杂度为O(1)版本
|
||||||
class Solution:
|
class Solution:
|
||||||
def climbStairs(self, n: int) -> int:
|
def climbStairs(self, n: int) -> int:
|
||||||
@ -275,7 +275,7 @@ class Solution:
|
|||||||
return dp[1]
|
return dp[1]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Go
|
### Go
|
||||||
```Go
|
```Go
|
||||||
func climbStairs(n int) int {
|
func climbStairs(n int) int {
|
||||||
if n==1{
|
if n==1{
|
||||||
@ -303,7 +303,7 @@ var climbStairs = function(n) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
TypeScript
|
### TypeScript
|
||||||
|
|
||||||
> 爬2阶
|
> 爬2阶
|
||||||
|
|
||||||
@ -447,7 +447,26 @@ public class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Rust
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn climb_stairs(n: i32) -> i32 {
|
||||||
|
if n <= 2 {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
let mut a = 1;
|
||||||
|
let mut b = 2;
|
||||||
|
let mut f = 0;
|
||||||
|
for i in 2..n {
|
||||||
|
f = a + b;
|
||||||
|
a = b;
|
||||||
|
b = f;
|
||||||
|
}
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user