xinyu04

导航

LeetCode 198. House Robber DP

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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Solution

很显然的一个思路就是开一维表示选了还是没选当前的数:\(dp[i][0]\) 表示以 \(i\) 结尾的序列,没选 \(i\) 的最大值,\(dp[i][1]\) 则是表示选了第 \(i\) 个。对于转移方程:

\[\begin{align} dp[i][0] &= \max(dp[i-1][0],dp[i-1][1])\\ dp[i][1] &= dp[i-1][0] + nums[i] \end{align} \]

点击查看代码
class Solution {
private:
    int dp[105][2];
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        if(n==1)return nums[0];
        else{
            dp[0][1] = nums[0];
            dp[0][0] = 0;
            for(int i=1;i<n;i++){
                dp[i][0] = max(dp[i-1][0],dp[i-1][1]);
                dp[i][1] = dp[i-1][0]+nums[i];
            }
            return max(dp[n-1][0],dp[n-1][1]);
        }
    }
};

posted on 2022-05-12 17:30  Blackzxy  阅读(16)  评论(0编辑  收藏  举报