当前位置:网站首页>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
边栏推荐
- Input file upload
- Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
- Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]
- Compare the performance of query based on the number of paging data that meet the query conditions
- Shell-sort命令的使用
- Baidu Map 3D rotation and tilt angle adjustment
- Baidu Map Case - Zoom component, map scale component
- 1-4 configuration executable script of nodejs installation
- ASP. NET CORE3. 1. Solution to login failure after identity registers users
- Generating access keys using JSON webtoken
猜你喜欢
随机推荐
Header built-in object
Perception of linear algebra 2
Simulation of infrared wireless communication based on 51 single chip microcomputer
Why do some people say SCM is simple and I have to learn it so hard?
Detailed explanation of C webpai route
Using quartz under. Net core - calendar of [6] jobs and triggers
1-5 nodejs commonjs specification
快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
Low code development platform sorting
node中,如何手动实现触发垃圾回收机制
freeCodeCamp----shape_ Calculator exercise
双闭环直流调速系统matlab/simulink仿真
[difference between Oracle and MySQL]
[PROJECT] small hat takeout (8)
El date picker limits the selection range from the current time to two months ago
Metaprogramming, proxy and reflection
Shell-awk命令的使用
The system cannot be started after AHCI is enabled
SiteServer CMS5. 0 Usage Summary
Shell-sed命令的使用









