LeetCode 题解(121): House Robber

题目:

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 andit 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 tonightwithout alerting the police.

题解:

这题的设定也是醉了。简单的动态规划。

C++版:

class Solution {
public:
    int rob(vector<int>& nums) {
        int globalMax = 0;
        vector<int> robber(nums.size(), 0);
        for(int i = 0; i < nums.size(); i++) {
            robber[i] = nums[i];
            int localMax = robber[i];
            for(int j = i - 2; j >= 0; j--) {
                if(robber[i] + robber[j] > localMax)
                    localMax = robber[i] + robber[j];
            }
            robber[i] = localMax;
            if(localMax > globalMax)
                globalMax = localMax;
        }
        return globalMax;
    }
};

Java版:

public class Solution {
    public int rob(int[] nums) {
        int global = 0;
        int[] robber = new int[nums.length];
        for(int i = 0; i < nums.length; i++) {
            int local = nums[i];
            robber[i] = nums[i];
            for(int j = i - 2; j >= 0; j--) {
                if(robber[i] + robber[j] > local)
                    local = robber[i] + robber[j];
            }
            robber[i] = local;
            if(local > global)
                global = local;
        }
        return global;
    }
}

Python版:

class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def rob(self, nums):
        robber = [0] * len(nums)
        rob = 0
        for i in range(len(nums)):
            robber[i] = nums[i]
            local = nums[i]
            for j in range(0, i - 1):
                local = local if robber[i] + robber[j] <= local else robber[i] + robber[j]
            robber[i] = local
            if local > rob:
                rob = local
        return rob
                


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值