算法系列——House Robber

来源:互联网 发布:天刀怎样下载捏脸数据 编辑:程序博客网 时间:2024/06/01 07:47

题目描述

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.

解题思路

递归+记忆化搜索

可以采用递归方法+记忆化搜索的方案,尝试抢劫当前房子i和和下个房子i+2,不断更新Max值,同时采用记忆数组 保存中间计算值。

动态规划

思路:因为不能抢劫挨着的店家, 所以这道题的本质相当于在一列数组中取出一个或多个不相邻数,使其和最大,使用动态规划。 举例子{1,2,3,4}, f[i]表示到第i家能偷窃的最大钱数,f[0] = nums[0], f[1] = max(nums[0], nums[1]), f[2]有两种可能,就是只取f[1]或者取f[0] + f[2]. 所以递推公式是:
f[i] = Math.max(f[i - 2] + nums[i], f[i - 1]);

时间复杂度: O(n)
空间复杂度: O(n)

程序实现

递归+记忆化搜索

class Solution {    //记忆数组    private int[] memo;    public int rob(int[] nums) {        memo=new int[nums.length];        Arrays.fill(memo,-1);        return tryRob(nums,0);    }    private int tryRob(int[] nums,int index){        if(index>=nums.length)            return 0;        if(memo[index]!=-1)            return memo[index];        int res=0;        for(int i=index;i<nums.length;i++)            res=Math.max(res,nums[i]+tryRob(nums,i+2));        memo[index]=res;        return res;    }}

动态规划

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