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
                


你可能感兴趣的:(Algorithm,LeetCode,面试题)