赞
踩
动态规划理论基础(主要就是确定动态规划的几个步骤)
- class Solution {
- public:
- int fib(int n) {
- if(n == 0) return 0;
- if(n == 1) return 1;
- int dp1 = 0;
- int dp2 = 1;
- int dp3 = 0;
- for(int i = 2;i <= n;i++) {
- dp3 = dp1 + dp2;
- dp1 = dp2;
- dp2 = dp3;
- }
- return dp3;
- }
- };
- class Solution {
- public:
- int climbStairs(int n) {
- if(n == 1) return 1;
- if(n == 2) return 2;
- int dp1 = 1;
- int dp2 = 2;
- int dp3 = 0;
- for(int i = 3;i <= n;i++) {
- dp3 = dp1 + dp2;
- dp1 = dp2;
- dp2 = dp3;
- }
- return dp3;
- }
- };
题目3:746. 使用最小花费爬楼梯 - 力扣(LeetCode)
- class Solution {
- public:
- int minCostClimbingStairs(vector<int>& cost) {
- vector<int> dp(cost.size() + 1);
- if(cost.size() == 1) return cost[0];
- dp[0] = 0;
- dp[1] = 0;
- for(int i = 2;i <= cost.size();i++) {
- dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
- }
- return dp[cost.size()];
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。