本文主要是介绍代码随想录算法训练营第三十九天|198.打家劫舍、,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:198. 打家劫舍 - 力扣(LeetCode)
思路:因为隔一家才能取,所以当前最大的价值要么是dp[i-2] + nums[i] 或者是 dp[i-1]
class Solution(object):def rob(self, nums):""":type nums: List[int]:rtype: int"""dp = [0] * len(nums)if (len(nums) == 1):return nums[0]dp[0] = nums[0]dp[1] = max(nums[0], nums[1])for i in range(2, len(nums)):dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])return dp[len(nums) - 1]
题目链接:198. 打家劫舍 - 力扣(LeetCode)
思路:由于数组的尾巴和首部相连,所以尾部和首部不能同时采用。所以要拆分成两个dp来做,一个是除去首元素,另一个是除去尾元素。
class Solution(object):def rob(self, nums):""":type nums: List[int]:rtype: int"""if len(nums) == 1:return nums[0]dp_1 = [0] * len(nums)dp_1[0] = nums[0]dp_1[1] = max(nums[0], nums[1])dp_2 = [0] * len(nums)dp_2[1] = nums[1]for i in range(2, len(nums) - 1):dp_1[i] = max(dp_1[i-2] + nums[i], dp_1[i-1])for i in range(2, len(nums)):dp_2[i] = max(dp_2[i-2] + nums[i], dp_2[i-1])return max(dp_1[len(nums) - 2], dp_2[len(nums) - 1])
题目链接:337. 打家劫舍 III - 力扣(LeetCode)
class Solution(object):def rob(self, nums):""":type nums: List[int]:rtype: int"""dp = [0] * len(nums)if (len(nums) == 1):return nums[0]dp[0] = nums[0]dp[1] = max(nums[0], nums[1])for i in range(2, len(nums)):dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])return dp[len(nums) - 1]
这篇关于代码随想录算法训练营第三十九天|198.打家劫舍、的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!