198. House Robber

来源:互联网 发布:php文件发送post请求 编辑:程序博客网 时间:2024/06/06 18:31

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];}
原创粉丝点击