198. 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 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.

递归+记忆化搜索

class Solution {
private:
    // memo[i] ,考虑从[i,nums.size())偷取得到价值最大的房子
    vector<int> memo;

    // 考虑从[index,nums.size())偷取得到价值最大的房子,返回最大的价值
    int tryRob(const vector<int>& nums, int index){

        // 递归终止,没有房子可以偷取
        if (index >= nums.size())return 0;

        // 记忆化搜索
        if (memo[index]!=-1)
            return memo[index];

        // 递归过程,即是状态转移过程
        int res = 0;
        for (int i = index; i < nums.size(); i++){
            res = max(res, nums[i] + tryRob(nums,i + 2));
        }
        memo[index] = res; //记忆化存储

        return res;
    }

public:
    // 递归 + 记忆化搜索
    int rob(vector<int>& nums) {
        memo = vector<int>(nums.size(), -1);
        return tryRob(nums, 0);
    }
};

动态规划

下面考虑两种不同的状态,对问题进行求解

状态1

memo[i][i..n1]

状态转移方程:
memo[i]=max{num[i]+memo[i+2],num[i+1]+memo[i+3],...,num[n1]}memo[0]

// 动态规划
int rob(vector<int>& nums) {
    int n = nums.size();
    if (n == 0)return 0;

    // memo[i] ,表示考虑偷取[i..n-1]个房子的最大价值
    vector<int> memo = vector<int>(n, -1);

    // 对基础问题进行设置,memo[n-1] ,也就是考虑偷取[n-1,n-1],肯定直接偷取是最大的价值
    memo[n - 1] = nums[n - 1];

    // 由基础问题自底向上的求解问题
    // 下一个要求解的问题也就是从n-2开始了,最后一个问题就是要求解memo[0]
    for (int i = n - 2; i >= 0; i--){
        for (int j = i; j < n; j++)
            // j+2 有可能越界,所以要判断一下
            memo[i] = max(memo[i], nums[j] + (j + 2 < n ? memo[j + 2] : 0));
    }
    return memo[0];
}
状态2

memo[i][0..i]

状态转移方程:
memo[i]=max{num[i]+memo[i2],num[i1]+memo[i3],...,num[0]}memo[n1]

// 动态规划 memo[i]表示,考虑偷取[0..i]的房子获取的最大收益
int rob2(vector<int>& nums) {
    int n = nums.size();
    if (n == 0)return 0;

    // memo[i] ,表示考虑偷取[0..i]个房子的最大价值
    vector<int> memo(n, -1);

    // 对基础问题进行设置,memo[0] ,也就是考虑偷取[0,0],肯定直接偷取是最大的价值
    memo[0] = nums[0];

    // 由基础问题自底向上的求解问题
    // 下一个要求解的问题也就是从1开始了,最后一个问题就是要求解memo[n-1]
    for (int i = 1; i <= n - 1; i++){
        // 逐层求解memo[i]
        for (int j = i; j >= 0; j--)
            memo[i] = max(memo[i], nums[j] + (j - 2 >= 0 ? memo[j - 2] : 0));
    }
    return memo[n - 1];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值