-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClimbingStairs_70.cpp
69 lines (52 loc) · 1.23 KB
/
ClimbingStairs_70.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 70. Climbing Stairs
~ Link : https://leetcode.com/problems/climbing-stairs/
*/
// Top-Down Approach (Memoization)
/*
class Solution {
public:
int dp[50];
int climbStairsUtil(int n) {
if (n <= 2)
return n;
if (dp[n] != -1)
return dp[n];
return dp[n] = climbStairsUtil(n - 1) + climbStairsUtil(n - 2);
}
int climbStairs(int n) {
memset(dp, -1, sizeof(dp));
return climbStairsUtil(n);
}
};
*/
// Bottom-Up Approach (Tabulation)
/*
class Solution {
public:
int dp[50];
int climbStairs(int n) {
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; ++i)
dp[i] = dp[i - 1] + dp[i - 2];
return dp[n];
}
};
*/
// Bottom-Up Approach (Without using dp array, O(1) space)
class Solution {
public:
int climbStairs(int n) {
if (n <= 2)
return n;
int first = 1, second = 2, res = 0;
for (int i = 3; i <= n; ++i) {
res = first + second;
first = second;
second = res;
}
return res;
}
};