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?
Note: Given n will be a positive integer.
首先是递归的算法,但是会超时
int climbStairs(int n) {if (n <= 0)return 0;else if (n == 1)return 1;else if (n == 2)return 2;return climbStairs(n - 1) + climbStairs(n - 2);
}
接着用一个数组存储到第i步有多少种走法,但是这样的空间复杂度为O(n);
int climbStairs(int n) {vector<int>my;if (n <= 0)return 0;else if (n == 1)return 1;else if (n == 2)return 2;my.push_back(0);my.push_back(1);my.push_back(2);for (int i = 3; i <= n; i++){my.push_back(my[i - 1] + my[i - 2]);}return my[n];
}
最后,将空间复杂度降为O(1);
int climbStairs(int n) {if (n == 0)return 0;if (n == 1)return 1;if (n == 2)return 2;int pre = 1, cur = 2, next = 0;for (int i = 3; i <= n; i++){next = pre + cur;pre = cur;cur = next;}return cur;
}