Last active
December 26, 2018 01:09
-
-
Save qiaoxu123/b9b6797712ee26c9622399a4d685bb39 to your computer and use it in GitHub Desktop.
失败。。 - [参考地址1](https://leetcode.com/problems/min-cost-climbing-stairs/discuss/110111/Easy-to-understand-C%2B%2B-using-DP-with-detailed-explanation)
- [参考地址2](https://leetcode.com/problems/min-cost-climbing-stairs/discuss/160791/4ms-c%2B%2B-simple-ap
This file contains hidden or 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
//测试性能:Runtime: 12 ms, faster than 26.44% | |
class Solution { | |
public: | |
int minCostClimbingStairs(vector<int>& cost) { | |
int n=(int)cost.size(); | |
vector<int> dp(n); | |
dp[0]=cost[0]; | |
dp[1]=cost[1]; | |
for (int i=2; i<n; ++i) | |
dp[i]=cost[i]+min(dp[i-2],dp[i-1]); | |
return min(dp[n-2],dp[n-1]); | |
} | |
}; |
This file contains hidden or 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
//测试性能:Runtime: 12 ms, faster than 26.44% | |
class Solution { | |
public: | |
int minCostClimbingStairs(vector<int>& cost) { | |
int b=cost[1],c=cost[0]; | |
for (int i=2,a; i<cost.size(); ++i,c=b,b=a) a=cost[i]+min(b,c); | |
return min(b,c); | |
} | |
}; |
This file contains hidden or 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
//测试性能:Runtime: 16 ms, faster than 4.28% | |
class Solution { | |
public: | |
int minCostClimbingStairs(vector<int>& cost) { | |
return go(cost, cost.size()); | |
} | |
private: | |
unordered_map<int,int> memo; | |
int go(vector<int>& c, int n){ | |
if (memo.count(n)) return memo[n]; | |
if (n<=1) return memo[n]=c[n]; | |
return memo[n]=(n==c.size() ? 0 : c[n])+min(go(c,n-2),go(c,n-1)); | |
} | |
}; |
This file contains hidden or 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
//测试性能:Runtime: 4 ms, faster than 100.00% | |
class Solution { | |
public: | |
int minCostClimbingStairs(vector<int>& cost) { | |
int prev1 = 0, prev2 = 0; | |
for (int i=2; i<=cost.size(); i++) | |
{ | |
int temp = min(cost[i-1] + prev1, cost[i-2] + prev2); | |
prev2 = prev1; | |
prev1 = temp; | |
} | |
return prev1; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment