多味的LeetCode --- 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

解題思路1:

在這裏插入圖片描述


代碼1:

python寫法:

import numpy as np
class Solution(object):
    def rob(self, nums):
        n = len(nums)
        
        f = np.zeros(n+1, dtype = int)
        g = np.zeros(n+1, dtype = int)

        for i in range(1, n+1):
            f[i] = max(f[i-1], g[i-1])
            g[i] = nums[i-1] + f[i-1]  # 第i個數在nums中是i-1,nums中的小標從0開始

        return max(f[n], g[n])

C++寫法:

class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        vector<int> f(n+1),g(n+1);
        for(int i = 1; i <= n; i++){
            f[i] = max(f[i-1], g[i-1]);
            g[i] = nums[i-1] + f[i-1];
        }
        return max(f[n], g[n]);
    }
};


參考鏈接:

https://www.bilibili.com/video/BV15441117yb?from=search&seid=16255148537935748434


題目來源:

https://leetcode-cn.com/problems/house-robber

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章