Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2017 from fwqaaq/patch-33
Browse files Browse the repository at this point in the history
Update 0509.斐波那契数.md 修改 rust 错误代码
  • Loading branch information
youngyangyang04 authored Apr 27, 2023
2 parents 2bc7ea0 + e1e695e commit f979407
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions problems/0509.斐波那契数.md
Original file line number Diff line number Diff line change
Expand Up @@ -347,26 +347,32 @@ int fib(int n){
### Rust
动态规划:
```Rust
pub fn fib(n: i32) -> i32 {
let n = n as usize;
let mut dp = vec![0; 31];
dp[1] = 1;
for i in 2..=n {
dp[i] = dp[i - 1] + dp[i - 2];
impl Solution {
pub fn fib(n: i32) -> i32 {
if n <= 1 {
return n;
}
let n = n as usize;
let mut dp = vec![0; n + 1];
dp[1] = 1;
for i in 2..=n {
dp[i] = dp[i - 2] + dp[i - 1];
}
dp[n]
}
dp[n]
}
```

递归实现:
```Rust
pub fn fib(n: i32) -> i32 {
//若n小于等于1,返回n
f n <= 1 {
return n;
impl Solution {
pub fn fib(n: i32) -> i32 {
if n <= 1 {
n
} else {
Self::fib(n - 1) + Self::fib(n - 2)
}
}
//否则返回fib(n-1) + fib(n-2)
return fib(n - 1) + fib(n - 2);
}
```

Expand Down

0 comments on commit f979407

Please sign in to comment.