当前位置:网站首页>动态规划每日一练(3)
动态规划每日一练(3)
2022-08-02 08:40:00 【恶龙咆哮@~】
打家劫舍
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
题解:如果房屋数量大于两间,应该如何计算能够偷窃到的最高总金额呢?对于第 k~(k>2)k (k>2) 间房屋,有两个选项:
(1)偷窃第 kk 间房屋,那么就不能偷窃第 k-1k−1 间房屋,偷窃总金额为前 k-2k−2 间房屋的最高总金额与第 kk 间房屋的金额之和。
(2)不偷窃第 kk 间房屋,偷窃总金额为前 k-1k−1 间房屋的最高总金额。
dp[i]=max(dp[i−2]+nums[i],dp[i−1])
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n==0)
{
return 0;
}
if(n==1)
{
return nums[0];
}
vector<int>dp(n+1);
dp[0]=nums[0];
dp[1]=max(nums[0],nums[1]);
for(int i=2;i<n;i++)
{
dp[i]=max(dp[i-1],dp[i-2]+nums[i]);
}
return dp[n-1];
}
};
在上述题目中加入一个条件:第一个房子挨着最后一个房子,即房子围成一个圆,问题又该如何解决?
解题:可以理解为第一个房间和第二个房间不能同时进入,这时候可以分为两个部分,有第一个无最后一个房间和有最后一个房间没有第一个房间,再比较他们之间的较大值
class Solution {
public:
int robfun(vector<int>& nums,int start,int end)
{
int first=nums[start];
int second=max(nums[start+1],nums[start]);
for(int i=start+2;i<=end;i++)
{
int cur=second;
second=max(second,first+nums[i]);
first=cur;
}
return second;
}
int rob(vector<int>& nums) {
int n=nums.size();
if(n==0)
{
return 0;
}
if(n==1)
{
return nums[0];
}
if(n==2)
{
return max(nums[0],nums[1]);
}
return max(robfun(nums,0,n-2),robfun(nums,1,n-1));
}
};
边栏推荐
- Pycharm (1) the basic use of tutorial
- Redisson的看门狗机制
- Biotin-C6-amine|N-biotinyl-1,6-hexanediamine|CAS: 65953-56-2
- spark:商品热门品类TOP10统计(案例)
- day_05_pickel 和 json
- (Note) AXIS ACASIS DT-3608 Dual-bay Hard Disk Array Box RAID Setting
- How Engineers Treat Open Source --- A veteran engineer's heartfelt words
- postman下载安装汉化及使用
- openpyxl 单元格合并
- Technology Cloud Report: To realize the metaverse, NVIDIA starts from building an infrastructure platform
猜你喜欢
随机推荐
构建Flink第一个应用程序
What is the function of the import command of the page directive in JSP?
[OC学习笔记]Block三种类型
High imitation [Huawei consumer business official website] and wonderful animation analysis: practice embedding JS code in low-code platform
HCIP笔记第十三天
恋爱十不要
R language plotly visualization: plotly visualizes the scatter plot of the actual value of the regression model and the predicted value of the regression, analyzes the prediction performance of the re
shell脚本
js函数防抖和函数节流及其使用场景
openpyxl 单元格合并
RetinaFace: Single-stage Dense Face Localisation in the Wild
In a recent build figure SLAM, and locate the progress
向量组的线性相关性
How to use postman
Docker内MySQL主从复制学习,以及遇到的一些问题
下一个排列
mysql 中 in 的用法
编程与哲学(2)——输出是为了更好的输入
ip地址那点事(二)
自定义View实现波浪荡漾效果


![[OC学习笔记]ARC与引用计数](/img/56/033cfc15954567d63d987d91ca8d63.png)

![Detailed explanation of calculation commands in shell (expr, (()), $[], let, bc )](/img/3c/5cc4d16b9b525997761445f32802d5.png)





