代码随想录算法训练营第三十一天| 509. 斐波那契数 70. 爬楼梯 746. 使用最小花费爬楼梯

 509. 斐波那契数 

思路:

运用动态规划的思想

1,先定义一个数组

2,初始化

3,递推公式

4,遍历

代码:

 1 int fib(int n)
 2 {
 3     if (n == 0) return 0;
 4     if (n == 1) return 1;
 5     
 6     vector<int> selected(n+1);
 7     selected[0] = 0;
 8     selected[1] = 1;
 9 
10     for (int i = 2; i <= n; i++)
11     {
12         selected[i] = selected[i - 1] + selected[i - 2];
13     }
14 
15     return selected.back();
16 }

  70. 爬楼梯

难点:

发现nums[i]=nums[i-1]+nums[i-2]

代码:

 1 int climbStairs(int n) {
 2     if (n == 0) return 0;
 3     if (n == 1) return 1;
 4     if (n == 2) return 2;
 5 
 6 
 7     vector<int> nums(n+1, 0);
 8     nums[1] = 1;
 9     nums[2] = 2;
10 
11     for (int i = 3; i < nums.size(); i++)
12     {
13         nums[i] = nums[i - 1] + nums[i - 2];
14     }
15 
16     return nums[n];
17 
18 }

 746. 使用最小花费爬楼梯 

难点:

  1. 明白题意,到了最后一个节点仍然不是顶楼,还是要上去
  2. 需要自己花一个楼梯
  3. 重点思考数组的定义是什么,一般是题目结果返回的定义

代码

 1 int minCostClimbingStairs(vector<int>& cost) {
 2     if (cost.size() == 0) return 0;
 3     if (cost.size() == 1) return 0;
 4     
 5     vector<int> result(cost.size() + 1, 0);
 6 
 7     //不用考虑要不要跨过哪个,直接是要哪个
 8     for (int i = 2; i < result.size(); i++)
 9     {
10         result[i] = min(result[i - 1] + cost[i - 1], result[i - 2] + cost[i - 2]);
11     }
12 
13     return result.back();
14 }

 

posted @ 2023-07-14 10:16  博二爷  阅读(4)  评论(0编辑  收藏  举报