59 - 198 打家劫舍
题目
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
示例 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 。
解答
动态规划
作者:LeetCode
链接:https://leetcode-cn.com/problems/house-robber/solution/da-jia-jie-she-by-leetcode/
感觉有点递归的思想。不是去计算所有不同选择下的最大值,而是把每间屋子作为一个节点,记录下这间屋子所获得的最大金额。然后每次都是以此来作比较。
var rob = function (nums) {
let prevMax = 0
curMax = 0
for (const item of nums) {
let temp = curMax
curMax = Math.max(prevMax + item, curMax)
prevMax = temp
}
return curMax
};
Runtime: 52 ms, faster than 72.92% of JavaScript online submissions for House Robber.
Memory Usage: 33.8 MB, less than 76.19% of JavaScript online submissions for House Robber.
每次偷房子,都要比较隔一个屋子的最大值,和相邻屋子的最大值。
func rob(nums []int) int {
var preMax, curMax int
for _, elem := range nums {
temp := curMax
curMax = int(math.Max(float64(preMax+elem), float64(curMax)))
preMax = temp
}
return curMax
}
Runtime: 0 ms, faster than 100.00% of Go online submissions forHouse Robber.
Memory Usage: 2 MB, less than 100.00% of Go online submissions forHouse Robber.
go的max必须是float64,所以还要转一下感觉很麻烦😂
一开始以为只能偷或奇或偶,但好像可以隔两个房间偷。
Last updated
Was this helpful?