70. Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
4. 1 step + 1 step + 1 step
5. 1 step + 2 steps
6. 2 steps + 1 step
https://www.youtube.com/watch?v=LpsDWvkd-4Q
这道题是Fibonacci的应用:
f
(
0
)
=
1
f(0) = 1
f(0)=1
f
(
1
)
=
1
f(1) = 1
f(1)=1
f
(
2
)
=
f
(
1
)
+
f
(
0
)
f(2) = f(1) + f(0)
f(2)=f(1)+f(0)
f
(
3
)
=
f
(
2
)
+
f
(
1
)
f(3) = f(2) + f(1)
f(3)=f(2)+f(1)
⋮
\vdots
⋮
f
(
n
)
=
f
(
n
−
1
)
+
f
(
n
−
2
)
f(n) = f(n-1) + f(n-2)
f(n)=f(n−1)+f(n−2)
方法1: DP
code
易错点:
- 终止条件
i < n + 1;
class Solution {
public:
int climbStairs(int n) {
vector<int> myTable(n + 1);
myTable[0] = 1;
myTable[1] = 1;
for (int i = 2; i < n + 1; i++){
myTable[i] = myTable[i - 1] + myTable[i - 2];
}
return myTable[n];
}
};
方法2: recursion + memoize
code
// memoize
class Solution {
public:
int climbStairs(int n) {
myTable = vector<int> (n + 1, 0);
return climbHelper(n);
}
private:
vector<int> myTable;
int climbHelper(int n){
if (n < 2) return 1;
if (myTable[n] > 0) return myTable[n];
myTable[n] = climbHelper(n - 1) + climbHelper(n - 2);
return myTable[n];
}
};
方法3: O(1) space complexity
这种方法是因为注意到Fibonacci只需要用到前两个数,所以用两个变量one
, two
来记录
f
(
n
−
1
)
,
f
(
n
−
2
)
f(n -1), f(n - 2)
f(n−1),f(n−2).
易错点:
- 更新顺序
- 终止条件
i < n + 1;
// O(1) space
class Solution {
public:
int climbStairs(int n) {
int one = 1;
int two = 1;
int cur = 1;
for (int i = 2; i < n + 1; i++){
cur = one + two;
two = one;
one = cur;
}
return cur;
}
};