1. 程式人生 > >198. 打家劫舍 | House Robber

198. 打家劫舍 | House Robber

con 整數 clas nal inpu 影響 pla represent 如果

ou are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

你是一個專業的小偷,計劃偷竊沿街的房屋。每間房內都藏有一定的現金,影響你偷竊的唯一制約因素就是相鄰的房屋裝有相互連通的防盜系統,如果兩間相鄰的房屋在同一晚上被小偷闖入,系統會自動報警。

給定一個代表每個房屋存放金額的非負整數數組,計算你在不觸動警報裝置的情況下,能夠偷竊到的最高金額。

示例 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 。

12ms
 1 class Solution {
 2     func rob(_ nums: [Int]) -> Int {
 3         var curMax = 0
 4         var preMax = 0
 5         for num in nums 
 6         {
 7             let temp = curMax
 8             curMax = max(curMax, preMax + num)
 9             preMax = temp
10         }
11         return curMax
12     }
13 }

8ms

 1 class Solution {
 2     func rob(_ nums: [Int]) -> Int {
 3         
 4         if nums.count <= 0 {
 5             return 0
 6         }
 7         
 8         var last: Int = 0
 9         var now: Int = 0
10         
11         for i in 0...nums.count - 1 {
12             var temp = last
13             last = now
14             now = max(temp + nums[i],now)
15         }
16         return now
17     }
18 }

8ms

 1 class Solution {
 2     func rob(_ nums: [Int]) -> Int {
 3         var memo: [Int] = [Int](repeating: 0, count: nums.count)
 4         
 5         if nums.count == 0 {
 6             return 0
 7         } else if nums.count == 1 {
 8             return nums[0]
 9         } else if nums.count == 2 {
10             return max(nums[0], nums[1])
11         }
12         
13         memo[0] = nums[0]
14         memo[1] = max(nums[0], nums[1])
15               
16         for i in 2..<nums.count {
17             let value = nums[i]
18             memo[i] = max(memo[i - 2] + value, memo[i - 1])
19         }
20         print(memo)
21         
22         return memo[nums.count - 1]
23     }
24 }

198. 打家劫舍 | House Robber