方法一:暴力法
我们需要不断调用函数来模拟爬1阶和2阶的情况
int climbStairs(int n)
{
return re_climbStairs(0, n);
}
int re_climbStairs(int i,int n)
{
if (i > n){
return 0;
}
if (i == n){
return 1;
}
return re_climbStairs(i + 1, n) + re_climbStairs(i + 2, n);
}
结果
很显然,这个简单的递归函数时间复杂度为O(2^N),效率并不高。
不出意外地,它TLE了,挂在了倒数第二组数据。
方法二:记忆递归
上一个方法有很多重复计算,所以我们可以把每步的结果保存起来。
int climbStairs(int n)
{
int a[n + 1];
for (int i = 0; i < n + 1; i++){
a[i] = 0;
}
return re_climbStairs(0, n, a);
}
int re_climbStairs(int i, int n, int a[])
{
if (i > n){
return 0;
}
if (i == n){
return 1;
}
if (a[i] > 0){
return a[i];
}
a[i] = re_climbStairs(i + 1, n, a) + re_climbStairs(i + 2, n, a);
return a[i];
}
结果
出乎意料的快
方法三:动态规划
该问题可以分成多个子问题。
第 i 阶可以由以下两种情况得到:
int climbStairs(int n)
{
int dp[n + 1];
for (int i = 0; i < n + 1; i++){
dp[i] = 0;
}
if (n == 1){
return 1;
}
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i < n + 1; i++){
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
结果
方法四:打表
最快乐的解法哈哈哈哈哈哈哈
我们注意到这个函数的返回值为int
型,用上面方法测试可知:
n最大值为45,当n=46时,返回值就溢出了
所以…
int climbStairs(int n)
{
int result = 0;
switch(n){
case 1: result = 1; break;
case 2: result = 2; break;
case 3: result = 3; break;
case 4: result = 5; break;
case 5: result = 8; break;
case 6: result = 13; break;
case 7: result = 21; break;
case 8: result = 34; break;
case 9: result = 55; break;
case 10: result = 89; break;
case 11: result = 144; break;
case 12: result = 233; break;
case 13: result = 377; break;
case 14: result = 610; break;
case 15: result = 987; break;
case 16: result = 1597; break;
case 17: result = 2584; break;
case 18: result = 4181; break;
case 19: result = 6765; break;
case 20: result = 10946; break;
case 21: result = 17711; break;
case 22: result = 28657; break;
case 23: result = 46368; break;
case 24: result = 75025; break;
case 25: result = 121393; break;
case 26: result = 196418; break;
case 27: result = 317811; break;
case 28: result = 514229; break;
case 29: result = 832040; break;
case 30: result = 1346269; break;
case 31: result = 2178309; break;
case 32: result = 3524578; break;
case 33: result = 5702887; break;
case 34: result = 9227465; break;
case 35: result = 14930352; break;
case 36: result = 24157817; break;
case 37: result = 39088169; break;
case 38: result = 63245986; break;
case 39: result = 102334155; break;
case 40: result = 165580141; break;
case 41: result = 267914296; break;
case 42: result = 433494437; break;
case 43: result = 701408733; break;
case 44: result = 1134903170; break;
case 45: result = 1836311903; break;
}
return result;
}