【LeetCode】198. House Robber

来源:互联网 发布:苹果cms解析百度云 编辑:程序博客网 时间:2024/05/29 02:07

【题目】

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.

【分析】

题目意思是从一组整数数组中取数,不能取相邻的数,求取的数和的最大值。

对每个数字有两种选择:取或不取,返回这两种情况下和的最大值。解决的方法有两种:

第一种,从前往后扫描,用递归的思想解决,但这种情况对后面的和会重复计算,会超时;

第二种,从后往前扫描,用一个N维数组存储之前计算的结果,计算前面的和时可以利用后面的和。

【代码】

第一种

class Solution {    public int rob(int[] nums, int start){        if(start==nums.length) return 0;        else if(start==(nums.length-1)) return nums[start];        else if(start==(nums.length-2)) return nums[start]>nums[start+1]?nums[start]:nums[start+1];        int m1=rob(nums,start+2)+nums[start];        int m2=rob(nums,start+1);        return m1>m2?m1:m2;    }    public int rob(int[] nums) {        return rob(nums,0);    }}


第二种

class Solution {    public int rob(int[] nums) {        int[] m=new int[nums.length+2];        for(int i=0;i<m.length;++i) m[i]=0;        int end=nums.length-1;        while(end>=0){            if(end==nums.length-1){                m[end]=nums[end];            }else if(end==nums.length-2){                m[end]=nums[end]>m[end+1]?nums[end]:m[end+1];            }else{                int m1=nums[end]+m[end+2];                int m2=m[end+1];                m[end]=m1>m2?m1:m2;            }            --end;        }        return m[0];    }}