商汤科技的笔试题。n阶,步长1~m,有时间和内存限制。
基础题:
n阶楼梯,每次能走1或2阶,问走到n阶一共多少种走法。
法一:递归 很容易超时
f(0)=1,f(1)=1,f(n)=f(n-1)+f(n-2)
#include <stdio.h>
#include <iostream>
#include<Windows.h>
using namespace std;
long long climbStairs(int n)
{
if (n == 1)
return 1;
else if (n == 2)
return 2;
else if (n > 2)
return climbStairs(n - 1) + climbStairs(n - 2);
}
int main()
{
long long stepCount = 0;
DWORD start_time = GetTickCount();
stepCount = climbStairs(45); //40: 165580141 4.88s 45: 1836311903 53.99s
DWORD end_time = GetTickCount();
printf("%lld\n", stepCount);
cout << "The run time is: " << (end_time - start_time) / 1000.0 << " s!" << endl;
getchar();
return 0;
}
法二:递推 用空间换时间,避免了重复计算,时间快了很多倍