当前位置:网站首页>LeetCode--打家劫舍问题
LeetCode--打家劫舍问题
2022-07-31 23:58:00 【华为云】
打家劫舍
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
示例 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 。
提示:
0 <= nums.length <= 100
0 <= nums[i] <= 400
class Solution {private: int tryRob( vector<int> &nums, int index ) { if ( index >= nums.size() ) return 0; for( int i = index; i < nums.size(); i++ ) res = max( res, nums[i] + tryRob(nums, i + 2) ); return res; }public: int rob(vector<int>& nums) { return tryRob(nums, 0); }};
记忆化搜索
class Solution {private: // memo[i] 表示考虑抢劫 nums[i..n]所能获得的最大收益 vector<int> memo; int tryRob( vector<int> &nums, int index ) { if ( index >= nums.size() ) return 0; if ( memo[index] != -1) return memo[index]; int res = 0; for( int i = index; i < nums.size(); i++ ) res = max( res, nums[i] + tryRob(nums, i + 2) ); memo[index] = res; return res; }public: int rob(vector<int>& nums) { memo = vector<int>(nums.size(), -1); return tryRob(nums, 0); }};
动态规划
class Solution {public: int rob(vector<int>& nums) { int n = nums.size(); if ( n == 0) return 0; vector<int> memo(n, -1); memo[n-1] = nums[n-1]; for( int i = n - 2; i >= 0; i-- ) { for( int j = i; j < n; j++ ) { memo[i] = max( memo[i], nums[j] + (j+2 < n ? memo[j+2] : 0) ); } } return memo[0]; }};
改变对状态的定义:
考虑偷取[0…x]范围里的房子(函数的定义)
边栏推荐
- SVN server construction + SVN client + TeamCity integrated environment construction + VS2019 development
- 内核对设备树的处理
- NIO programming
- MySQL数据库‘反斜杠\’ ,‘单引号‘’,‘双引号“’,‘null’无法存储
- SQL injection Less54 (limited number of SQL injection + union injection)
- 标段参数说明
- 2022年CSP-J1 CSP-S1 第1轮初赛 报名指南
- Carefully organize 16 MySQL usage specifications to reduce problems by 80% and recommend sharing with the team
- thymeleaf迭代map集合
- 助力数字政府建设,中科三方构建域名安全保障体系
猜你喜欢
随机推荐
I don't know what to do with sync issues
cobaltstrike
日常--Kali开启SSH(详细教程)
thymeleaf迭代map集合
The difference between adding or not adding the ref keyword when a variable of reference type is used as a parameter in a method call in C#
内核对设备树的处理
Flutter教程之 02 Flutter 桌面程序开发入门教程运行hello world (教程含源码)
编程语言是什么
嵌入式开发没有激情了,正常吗?
网络安全--通过握手包破解WiFi(详细教程)
Shell常用脚本:Nexus批量上传本地仓库脚本
博弈论(Depu)与孙子兵法(42/100)
UOS统信系统 - WindTerm使用
2022年最新重庆建筑八大员(电气施工员)模拟题库及答案
vim的基本使用-命令模式
一体化步进电机在无人机自动机场的应用
一行代码解决CoreData托管对象属性变更在SwiftUI中无动画效果的问题
[QNX Hypervisor 2.2用户手册]9.16 system
Keil nRF52832 download failed
@JsonFormat(pattern="yyyy-MM-dd") time difference problem