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

 

题目大意

给定一个数组,从数组中挑选出一些数字使得数字最大, 要求不能挑选任意两个相邻的数字。

 

示例

E1

Input: [1,2,3,1]
Output: 4

E2

Input: [2,7,9,3,1]
Output: 12

 

解题思路

动态规划问题,设数组dp[n],其中dp[i]代表:到第i个数字可以选到的从0到i的最大组合的数值。

利用dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]),(PS:式子表示dp[i]的最大值为i - 1的最大值或i - 2的最大值加i的值)

即可知道dp[n - 1]为所求得的最后结果。

 

复杂度分析

时间复杂度:O(n)

空间复杂度:O(n)

 

代码

class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        //若n为0,1,2进行判断
        if(n == 0)
            return 0;
        if(n <= 2) {
            return n == 1 ? nums[0] : max(nums[0], nums[1]);
        }
        
        vector<int> dp(n + 1, 0);
        dp[0] = nums[0];
        dp[1] = max(nums[0], nums[1]);
        //进行dp最优状态转移
        for(int i = 2; i < n; i++) {
            dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
        }
        
        return dp[n - 1];
    }
};

 

posted @ 2019-06-06 15:09  你好哇傻小妞  阅读(97)  评论(0编辑  收藏  举报