LeetCode 198: House Robber

題目鏈接:

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

描述

You 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.

算法思想:

動態規劃算法:使用d[i]意味着在第i個商店之前可以搶劫的最大價值。對於每家商店,我們有兩個選擇:搶還是不搶。
(1)如果搶劫,d [i] = d [i-2] + nums [i],搶劫的店鋪不能連接。
(2)如果不搶劫,d [i] = d [i-1];
這個想法有點像0/1揹包。

源代碼

/*
Author:楊林峯
Date:2017.12.30
LeetCode(198):House Robber
*/
class Solution {
public:
    int rob(vector<int>& nums) {
        int sz = nums.size();
        int *d = new int[sz + 1];
        if(sz < 1)
            return 0;
        if(sz == 1)
            return nums[0];
        if(sz == 2)
            return max(nums[0],nums[1]);
        d[0] = nums[0];
        d[1] = max(nums[0],nums[1]);
        for(int i = 2;i < sz;i++)
        {
            d[i] = max(d[i - 2] + nums[i],d[i - 1]);
        }
        return d[sz - 1];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章