forked from Rohit0301/Compititive_programming_code
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request Rohit0301#63 from Jay179-sudo/Climb-Stairs
Added working code solution for the Leetcode Problem 'Min Cost Climbi…
- Loading branch information
Showing
1 changed file
with
37 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,41 @@ | ||
class Solution { | ||
public: | ||
int minCostClimbingStairs(vector<int>& cost) { | ||
int n=cost.size(); | ||
int dp[n]; | ||
dp[0]=cost[0]; | ||
dp[1]=cost[1]; | ||
for(int i=2;i<n;i++){ | ||
dp[i]=min(dp[i-1],dp[i-2])+cost[i]; | ||
int dp[1000]; | ||
int rec(int level, int size, vector<int> &cost) | ||
{ | ||
// this recurrence gives us the minimum cost of reaching the top of the floor | ||
|
||
// pruning | ||
if(level > size) | ||
{ | ||
return 1001; | ||
// we will return anything > 999 so that this partial-solution is never chosen | ||
} | ||
// base case | ||
|
||
if(level == size) | ||
{ | ||
return 0; | ||
} | ||
|
||
if(dp[level] != -1) | ||
{ | ||
return dp[level]; | ||
} | ||
return min(dp[n-1],dp[n-2]); | ||
|
||
// choices | ||
// choices will be to either take 1 step or two steps | ||
|
||
int ans = 0; | ||
|
||
ans = cost[level] + min(rec(level + 1, size, cost), rec(level + 2, size, cost)); | ||
|
||
// return and save | ||
dp[level] = ans; | ||
return ans; | ||
} | ||
int minCostClimbingStairs(vector<int>& cost) { | ||
memset(dp, -1, sizeof(dp)); | ||
return min(rec(1, cost.size(), cost), rec(0, cost.size(), cost)); | ||
} | ||
}; | ||
}; |