当前位置:网站首页>198. 打家劫舍-动态规划
198. 打家劫舍-动态规划
2022-04-23 17:32:00 【hequnwang10】
一、题目描述
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
示例 1:
输入:[1,2,3,1]
输出:4
解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
示例 2:
输入:[2,7,9,3,1]
输出:12
解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
偷窃到的最高金额 = 2 + 9 + 1 = 12 。
二、解题
动态规划
dp[i]表示下标为以i为下标时能偷到的最大值。
dp[i]=max(dp[i−2]+nums[i],dp[i−1])
class Solution {
public int rob(int[] nums) {
//解题思路比较简单 根据公式来算
//dp[i]=max(dp[i−2]+nums[i],dp[i−1])
int length = nums.length;
if(length == 0 || nums == null){
return 0;
}
if(length == 1){
return nums[0];
}
int[] dp = new int[length+1];
dp[1] = nums[0];
for(int i = 2;i<=length;i++){
dp[i] = Math.max(dp[i-2]+nums[i-1],dp[i-1]);
}
return dp[length];
}
}
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://blog.csdn.net/hequnwang10/article/details/124349870
边栏推荐
- PC uses wireless network card to connect to mobile phone hotspot. Why can't you surf the Internet
- Scope and scope chain in JS
- Preliminary understanding of promse
- For the space occupation of the software, please refer to the installation directory
- 读《Software Engineering at Google》(15)
- 1-1 NodeJS
- . net type transfer
- Open futures, open an account, cloud security or trust the software of futures companies?
- Promise (IV)
- Further study of data visualization
猜你喜欢
Collection of common SQL statements
Why do some people say SCM is simple and I have to learn it so hard?
For the space occupation of the software, please refer to the installation directory
If you start from zero according to the frame
Use of todesk remote control software
RPC核心概念理解
Future 用法详解
. net cross platform principle (Part I)
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
PC电脑使用无线网卡连接上手机热点,为什么不能上网
随机推荐
Understanding of RPC core concepts
Solution of Navicat connecting Oracle library is not loaded
Shell-awk命令的使用
Baidu Map Case - Zoom component, map scale component
PC uses wireless network card to connect to mobile phone hotspot. Why can't you surf the Internet
基于51单片机红外无线通讯仿真
Use of shell awk command
Metaprogramming, proxy and reflection
SiteServer CMS5. 0 Usage Summary
. net cross platform principle (Part I)
1-3 components and modules
Solution architect's small bag - 5 types of architecture diagrams
Input file upload
STM32 entry development board choose wildfire or punctual atom?
快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
Websocket (basic)
线性代数感悟之1
ClickHouse-表引擎
Basic case of Baidu map
双指针进阶--leetcode题目--盛最多水的容器