当前位置:网站首页>Daily practice of dynamic programming (3)
Daily practice of dynamic programming (3)
2022-08-02 09:07:00 【Dragon Roar @~】
打家劫舍
你是一个专业的小偷,计划偷窃沿街的房屋.每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警.
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额.
题解:如果房屋数量大于两间,应该如何计算能够偷窃到的最高总金额呢?对于第 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];
}
};
Add a condition to the above question:The first house is next to the last house,That is, the house forms a circle,how to solve the problem?
解题:It can be understood that the first room and the second room cannot be entered at the same time,This can be divided into two parts,There is first room without last room and there is last room without first room,Then compare the larger value between them
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));
}
};
边栏推荐
猜你喜欢
随机推荐
PyQt5 (a) PyQt5 installation and configuration, read from the folder and display images, simulation to generate the sketch image
如何建立私域流量?私域流量对企业有什么好处?
天地图给多边形加标注
动态规划每日一练(2)
Hikari连接池源码解读
构建Flink第一个应用程序
PostgreSQL learning summary (11) - PostgreSQL commonly used high-availability cluster solutions
Qt读取文件中内容(通过判断GBK UTF-8格式进行读取显示)
Gorilla Mux 和 GORM 的使用方法
sql concat(),如何才能拼接表的名字
普林斯顿微积分读本03第二章--编程实现函数图像绘制、三角学回顾
Openwrt_树莓派B+_Wifi中继
Flink 程序剖析
查看变量的数据格式
PyQt5(一) PyQt5安装及配置,从文件夹读取图片并显示,模拟生成素描图像
mysql 中 in 的用法
破解wifi密码 暴力破解 保姆式教学
PyCharm使用教程(详细版 - 图文结合)
力扣:第 304 场周赛
堪称神级的阿里巴巴“高并发”教程《基础+实战+源码+面试+架构》