Skip to content

Commit 56ba511

Browse files
committed
LeetCode打卡第十二天day1212_ClimbingStairs
1 parent e3f015e commit 56ba511

File tree

1 file changed

+130
-0
lines changed

1 file changed

+130
-0
lines changed

ClimbingStairs.md

+130
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
---
2+
Time:2019/4/12
3+
Title:Clibing Srairs
4+
Difficulty: Easy
5+
Author:小鹿
6+
---
7+
8+
9+
10+
## 题目:Climbing Stairs
11+
12+
You are climbing a stair case. It takes *n* steps to reach to the top.
13+
14+
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
15+
16+
**Note:** Given *n* will be a positive integer.
17+
18+
假设你正在爬楼梯。需要 *n* 阶你才能到达楼顶。
19+
20+
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
21+
22+
**注意:**给定 *n* 是一个正整数。
23+
24+
**Example 1:**
25+
26+
```
27+
Input: 2
28+
Output: 2
29+
Explanation: There are two ways to climb to the top.
30+
1. 1 step + 1 step
31+
2. 2 steps
32+
```
33+
34+
**Example 2:**
35+
36+
```
37+
Input: 3
38+
Output: 3
39+
Explanation: There are three ways to climb to the top.
40+
1. 1 step + 1 step + 1 step
41+
2. 1 step + 2 steps
42+
3. 2 steps + 1 step
43+
```
44+
45+
46+
47+
## slove
48+
49+
#### ▉ 算法思路
50+
51+
> 二种解决思路,第一利用递归;第二利用动态规划。
52+
>
53+
> 1)递归的实现方式:
54+
>
55+
> 首先,我们要知道递归使用应该满足的三个条件,之前在前边的题型中讲到过,后边我会整理成系列文章供大家方便学习。然后按照我们之前讲过的方式去写出递归公式,然后转化为递归的代码。我们会发现递归的时间复杂度为 O(2^n),我们是否还记得递归的缺点有一条就是警惕递归重复元素计算。就是因为有了重复元素的计算,导致了时间复杂度成指数的增长。
56+
>
57+
> 为了能够降低时间复杂度,我们可以用散列表来记录重复元素记录过的值,但是需要申请额外的空间进行存储,导致空间复杂度为O(n),时间复杂度降为O(n),也正是利用了空间换时间的思想。
58+
>
59+
> 2)动态规划的实现方式:
60+
>
61+
> 我们可以仔细发现上方的递归的方式还是可以优化的,我们换种方式去思考,从底向上去思考,其实我们计算一个值之存储之前的两个值就可以了(比如:计算 f(6) ,需要知道 f(5) 和 f(4) 的值就可以了),我们可以不用存储之前的值,此时可以将空间复杂度降为 O(1)。
62+
63+
64+
65+
#### ▉ 代码实现(递归)
66+
67+
> 优化后的递归实现。
68+
69+
```javascript
70+
//递归实现
71+
//时间复杂度为 O(n),空间复杂度为 O(n)
72+
var climbStairs = function(n) {
73+
let map = new Map();
74+
if(n === 1) return 1;
75+
if(n === 2) return 2;
76+
if(map.has(n)){
77+
return map.get(n);
78+
}else{
79+
let value = climbStairs(n - 1) +climbStairs(n - 2);
80+
map.set(n,value);
81+
return value;
82+
}
83+
};
84+
```
85+
86+
87+
88+
#### ▉ 代码实现(动态规划)
89+
90+
```javascript
91+
//动态规划
92+
//时间复杂度为O(n) 空间复杂度为O(1)
93+
var climbStairs = function(n) {
94+
if(n < 1) return 0;
95+
if(n === 1) return 1;
96+
if(n === 2) return 2;
97+
98+
let a = 1;
99+
let b = 2;
100+
let temp = 0;
101+
102+
for (let i = 3; i < n + 1; i++) {
103+
temp = a + b;
104+
a = b;
105+
b = temp;
106+
}
107+
return temp;
108+
}
109+
```
110+
111+
112+
113+
114+
115+
116+
117+
118+
119+
120+
121+
122+
123+
124+
125+
126+
127+
128+
129+
130+

0 commit comments

Comments
 (0)