-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path746MinCostClimbingStairs.cpp
executable file
·52 lines (40 loc) · 1.34 KB
/
746MinCostClimbingStairs.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
// Recursive Approach
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
return min(mincost(cost,0), mincost(cost,1));
}
int mincost(vector<int>&cost, int current){
if(current == cost.size()){
return 0;
}
if(current>cost.size()){
return 1001;
}
int single = cost[current] + mincost(cost,current+1);
int two = cost[current] + mincost(cost,current+2);
return min(single,two);
}
};
//Dp optimized using maps
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
return min(mincost(cost,0), mincost(cost,1));
}
unordered_map<int, int>map;
int mincost(vector<int>& cost, int current){
if(current == cost.size())
return 0;
if(current>cost.size())
return 1001;
//checking Overlapping Subproblem
int current_key = current;
if(map.find(current) != map.end())
return map[current_key];
int onejump = cost[current] + mincost(cost, current+1);
int twojump = cost[current] + mincost(cost, current+2);
map[current_key] = min(onejump, twojump);
return min(onejump, twojump);
}
};