Leetcode刷题90-198. 打家劫舍(C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/house-robber/]

198. House Robber

  • 1.Question
  • 2.Answer
  • 3.我的收获

1.Question

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.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

2.Answer

easy 类型题目。.
首先来总结一下动态规划的一般解题步骤:

  1. 首先确定 原问题子问题
    本题中,原问题是求n个房间的最优解,子问题是求前1个房间,前两个房间。。。前n-1个房间的最优解。
  2. 确认状态
    第i个状态即为前i个房间能够获得的最优解(即偷得的最大财宝)。
  3. 确认边界的状态
    前1个房间的最优解,就是第一个房间。
    前2个房间的最优解,就是两个房间的 最大值。
  4. 确定状态转移方程
    a. 选择第i个房间:第 i个房间 + 前 i-2 个房间的 最优解
    b. 不选择第i个房间:前 i-1 个房间的 最优解。

动态规划转移方程:
dp[i] = max(dp[i-2] + num[i], dp[i-1]); 其中 i >=3

AC代码如下:

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() == 0)
        {
            return 0;
        }
        if(nums.size() == 1)
        {
            return nums[0];
        }
        vector<int> dp(nums.size(), 0);  // 设第i个房间的 最优解为: dp[i]
        dp[0] = nums[0];
        dp[1] = max(nums[0], nums[1]);
        int i = 0;
        for(i = 2; i < nums.size(); ++i)
        {
            dp[i] = max(dp[i-2]+nums[i], dp[i-1]);
        }
        return dp[i-1]; //注意这地方别越界。也可以改写成 return dp[nums.size()-1];
    }
};

3.我的收获

感觉还是要系统的掌握知识。。。
比如这次的 动态规划 day2。。。
系统的学习之后,才能更加得心应手的运用~

2019/5/29 胡云层 于南京 90

你可能感兴趣的:(LeetCode从零开始,LeetCode,C++)