[LeetCode][动态规划]House Robber

来源:互联网 发布:淘宝店铺显示未开店 编辑:程序博客网 时间:2024/05/17 07:18

题目描述:

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.


思路:

前提:给定连续的数组,数组的顺序代表家庭的相邻关系,数组中的值代表当前索引下的家庭的财务值,限制是不能抢劫连续的两个家庭,求解如何能够抢劫到最大的财富值

过程:这是一个典型的动态规划的问题,对于每一个家庭来说,有抢与不抢两种状态,从第一个家庭开始,若当前状态为抢,抢劫财富值+当前家庭财富,若当前状态为不抢,抢劫财富值不变,取决于上一次不抢和抢之后最大的财富值,最终抢劫的最大值就是最后一个家庭抢之后的总财富值和不抢的总财富值的较大值,在动态规划中,当前状态取决于之前状态,只往前看,不往后看


代码实现:

public class Solution {    public int rob(int[] nums) {        if(nums == null || nums.length == 0){            return 0;        }        int n = nums.length;        int[] rob = new int[n];        int[] max = new int[n];                rob[0] = nums[0];        max[0] = 0;                for(int i = 1;i < n;i++){            rob[i] = max[i-1]+nums[i];            max[i] = Math.max(rob[i-1],max[i-1]);        }                return Math.max(rob[n-1],max[n-1]);    }}


0 0
原创粉丝点击