70.Climbing Stairs[Easy]
Description
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.
n阶台阶,每次可以上一步或两步,问一共有多少爬台阶的方法。
Solution
动态规划的问题。
每次可以选一步或者两步,当只有一级台阶的时候,只有一种方法(上一步);有两级台阶,两种选择(1+1/2+0)
当有3阶时,可以假设最后一步爬一级,那么剩下(3-1)级,有两种选择(已知条件);假设最后一步爬两级,那么剩下(3-2)级,有一种选择(已知条件)。所以一共有1+2=3种方法。
当有n阶的时候,我们可以利用n-1阶和n-2阶的情况,相当于n-1阶再爬一步和n-2阶再爬两步。所以n阶情况共有【n-1】+【n-2】种解法。
【n】表示n级台阶时有【n】种解法。
可以用一个数组来存,类似于斐波那契数列的求法。
Complexity analysis
O(n)
Code
class Solution {
public:
int climbStairs(int n) {
int size = n+1;
//注意不要溢出
if (size == 1) {
return 0;
} else if(size == 2) {
return 1;
} else if (size == 3) {
return 2;
}
arr[1] = 1;
arr[2] = 2;
for (int i = 3; i <= n; i++) {
arr[i] = arr[i-1] + arr[i-2];
}
return arr[n];
}
};