程序员面试金典——9.1上楼梯
Solution1:我的破答案,复杂度太高未能AC
递归的毛病就是复杂度太高!!!
class GoUpstairs {
public:
int countWays(int n) { //hin典型的递归啊~
// write code here
return my_count(n);
}
int my_count(int n) {
if(n == 1)
return 1;
else if(n == 2)
return 2;
else if(n == 3)
return 4;
else
return (my_count(n - 1) +
my_count(n - 2) +
my_count(n - 3))%
1000000007;
}
};
Solution2:真没想到这种上楼梯的题目还能用动态规划来做~~~
参考网址:https://www.nowcoder.com/profile/332470/codeBookDetail?submissionId=12674248
牛逼啊,真牛逼!!!
菜鸟同志!继续努力!
class GoUpstairs {
public:
int countWays(int n) {
int a[100000];
a[1] = 1;
a[2] = 2;
a[3] = 4;
for(int i=4;i<=n;i++)
a[i] = (a[i-1]+(a[i-2]+a[i-3])%1000000007) % 1000000007;
return a[n];
}
};