problem:
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?
Dynamic Programmingthinking:
(1)说实话,看到题第一反应使用 DFS ,但是深搜的时间复杂度为解个数的线性表达式,肯定会超时
(2)提示使用DP,时间复杂度为O(n),这道题的状态转移方程式很简单: a[i]=a[i-1]+a[i-2];唯一有问题的是初始化:a[0]=1,a[1]=2
提交试错时改正就是。
code:
class Solution {
public:
int climbStairs(int n) {
vector<int> a(n,0);
a[0]=1;
a[1]=2;
if(n<3)
return a[n-1];
for(int i=2;i<n;i++)
a[i]=a[i-1]+a[i-2];
return a[n-1];
}
};leetcode || 70、 Climbing Stairs
原文地址:http://blog.csdn.net/hustyangju/article/details/44937807