70. Climbing Stairs - cocoder39/coco39_LC GitHub Wiki
O(n) time and O(n) space
int climbStairs(int n) {
if (n <= 0) {
return 0;
}
vector<int> dp(n + 1); //dp[i] is ways of climbing to step i
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 2] + dp[i - 1];
}
return dp[n];
}
space complexity can be optimized
int climbStairs(int n) {
if (n <= 0) {
return 0;
}
if (n == 1 || n == 2) {
return n;
}
int twoStepBefore = 1; //n == 1
int oneStepBefore = 2; //n == 2
int res;
for (int i = 3; i <= n; i++) {
res = twoStepBefore + oneStepBefore;
twoStepBefore = oneStepBefore;
oneStepBefore = res;
}
return res;
}