Skip to content

Commit

Permalink
添加 0070.爬楼梯.md C语言版本
Browse files Browse the repository at this point in the history
  • Loading branch information
KingArthur0205 committed Jan 12, 2022
1 parent 014dbf0 commit 165fd42
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions problems/0070.爬楼梯.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,48 @@ var climbStairs = function(n) {
};
```

### C
```c
int climbStairs(int n){
//若n<=2,返回n
if(n <= 2)
return n;
//初始化dp数组,数组大小为n+1
int *dp = (int *)malloc(sizeof(int) * (n + 1));
dp[0] = 0, dp[1] = 1, dp[2] = 2;

//从前向后遍历数组,dp[i] = dp[i-1] + dp[i-2]
int i;
for(i = 3; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
//返回dp[n]
return dp[n];
}
```
优化空间复杂度:
```c
int climbStairs(int n){
//若n<=2,返回n
if(n <= 2)
return n;
//初始化dp数组,数组大小为3
int *dp = (int *)malloc(sizeof(int) * 3);
dp[1] = 1, dp[2] = 2;
//只记录前面两个台阶的状态
int i;
for(i = 3; i <= n; ++i) {
int sum = dp[1] + dp[2];
dp[1] = dp[2];
dp[2] = sum;
}
//返回dp[2]
return dp[2];
}
```


-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit 165fd42

Please sign in to comment.