Skip to content

Commit f6b37c9

Browse files
committed
DP on Mar 11
1 parent a1b091f commit f6b37c9

File tree

2 files changed

+75
-1
lines changed

2 files changed

+75
-1
lines changed

DP/70.climbing-stairs.cpp

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,16 @@
4343
class Solution {
4444
public:
4545
int climbStairs(int n) {
46-
46+
if(n==0)return 0;
47+
if(n==1)return 1;
48+
if(n==2)return 2;
49+
int a=1,b=2;
50+
for(int i=2;i<n;i++){
51+
int tmp=a+b;
52+
a=b;
53+
b=tmp;
54+
}
55+
return b;
4756
}
4857
};
4958

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
* @lc app=leetcode id=746 lang=cpp
3+
*
4+
* [746] Min Cost Climbing Stairs
5+
*
6+
* https://leetcode.com/problems/min-cost-climbing-stairs/description/
7+
*
8+
* algorithms
9+
* Easy (46.04%)
10+
* Total Accepted: 68.1K
11+
* Total Submissions: 147.6K
12+
* Testcase Example: '[0,0,0,0]'
13+
*
14+
*
15+
* On a staircase, the i-th step has some non-negative cost cost[i] assigned (0
16+
* indexed).
17+
*
18+
* Once you pay the cost, you can either climb one or two steps. You need to
19+
* find minimum cost to reach the top of the floor, and you can either start
20+
* from the step with index 0, or the step with index 1.
21+
*
22+
*
23+
* Example 1:
24+
*
25+
* Input: cost = [10, 15, 20]
26+
* Output: 15
27+
* Explanation: Cheapest is start on cost[1], pay that cost and go to the
28+
* top.
29+
*
30+
*
31+
*
32+
* Example 2:
33+
*
34+
* Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
35+
* Output: 6
36+
* Explanation: Cheapest is start on cost[0], and only step on 1s, skipping
37+
* cost[3].
38+
*
39+
*
40+
*
41+
* Note:
42+
*
43+
* cost will have a length in the range [2, 1000].
44+
* Every cost[i] will be an integer in the range [0, 999].
45+
*
46+
*
47+
*/
48+
class Solution
49+
{
50+
public:
51+
int minCostClimbingStairs(vector<int> &cost)
52+
{
53+
int s = cost.size();
54+
if (s == 0)
55+
return 0;
56+
if (s == 1)
57+
return cost[0];
58+
int a[] = {cost[0], cost[1]};
59+
for (int i = 2; i < s; i++)
60+
{
61+
a[i % 2] = min(cost[i] + a[0], cost[i] + a[1]);
62+
}
63+
return min(a[0], a[1]);
64+
}
65+
};

0 commit comments

Comments
 (0)