【Leetcode】爬楼梯
问题: 爬n阶楼梯,每次只能走1阶或者2阶,计算有多少种走法。 暴力计算+记忆化递归。 从位置 i 出发,每次走1阶或者2阶台阶,记录从位置 i 出发到目标 n 所有的走法数量,memoA[i] 。记录的数据可以重复使用,避免冗余计算。 时间复杂度:O(n)。每次计算从 i 位置出发到终点 n 的走法,共计算 n 次,即树形递归的大小为n。 空间复杂度:O(n)。使用了长度为 n 的数组。 clock_t start1, end1; class Solution { public: int climbStairs(int n) { int memo[n+1] = {0}; start1 = clock(); int result = climb_stairs(0, n, memo); end1 = clock(); cout << "cost time = " << (double)(end1 - start1) / CLOCKS_PER_SEC << endl; return result; } int climb_stairs(int i, int nums, int memoA[]) { if (i > nums) return 0; if (i == nums) return 1; if (memoA[i] > 0) return memoA[i]; memoA[i] =