题解 | #打家劫舍(二)#
打家劫舍(二)
https://www.nowcoder.com/practice/a5c127769dd74a63ada7bff37d9c5815
class Solution: def rob1(self , nums: List[int]) -> int: n = len(nums) if n == 0: return 0 elif n == 1: return nums[0] dp = [0]*n dp[0] = nums[0] dp[1] = max(nums[0], nums[1]) # 在进入循环前需要初始化两个 for i in range(2, n): dp[i] = max(dp[i-2]+nums[i], dp[i-1]) # 当前和隔一个的总钱数,和前一个的总钱数 return dp[-1] def rob(self , nums: List[int]) -> int: if len(nums) == 0: return 0 elif len(nums) == 1: return nums[0] return max(self.rob1(nums[1:]), self.rob1(nums[:-1]))