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];
    }
};

你可能感兴趣的:(leetcode,算法,动态规划,leetcode)