Skip to content

Commit

Permalink
添加 0509.斐波那契数.md C语言版本
Browse files Browse the repository at this point in the history
  • Loading branch information
KingArthur0205 committed Jan 12, 2022
1 parent d236296 commit 014dbf0
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions problems/0509.斐波那契数.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,38 @@ var fib = function(n) {
};
```

### C
动态规划:
```c
int fib(int n){
//当n <= 1时,返回n
if(n <= 1)
return n;
//动态开辟一个int数组,大小为n+1
int *dp = (int *)malloc(sizeof(int) * (n + 1));
//设置0号位为0,1号为为1
dp[0] = 0;
dp[1] = 1;

//从前向后遍历数组(i=2; i <= n; ++i),下标为n时的元素为dp[i-1] + dp[i-2]
int i;
for(i = 2; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
```
递归实现:
```c
int fib(int n){
//若n小于等于1,返回n
if(n <= 1)
return n;
//否则返回fib(n-1) + fib(n-2)
return fib(n-1) + fib(n-2);
}
```


-----------------------
Expand Down

0 comments on commit 014dbf0

Please sign in to comment.