leetcode 198. House Robber

本文介绍了一个经典的动态规划问题——打家劫舍。该问题要求在一个整数数组中找到最大的非相邻元素之和,模拟了抢劫者如何在不触动警报的前提下最大化收益。通过两种方法实现:一种使用数组进行动态规划;另一种则通过两个变量来优化空间复杂度。
摘要由CSDN通过智能技术生成
/*
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.

解题思路:dp

*/


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

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);
        dp[0] = nums[0];
        dp[1] = max(nums[0], nums[1]);
        for (size_t i = 2; i < nums.size(); ++i)
        {
            dp[i] = max(dp[i-1], dp[i-2]+nums[i]);//dp[i-1]:不抢这一家,dp[i-2]+nums[i]:抢这一家。
            //cout << dp[i] << " ";
        }
        //cout << endl;
        return dp[nums.size() - 1];
    }
    //空间优化
    int rob1(vector<int>& nums)
    {
        if (nums.size() == 0)
            return 0;
        if (nums.size() == 1)
            return nums[0];

        int pre = 0;    //对于i房间来说,保存的是前一个的最优解
        int cur = 0;    //对于i房间来说,保存的是当前最优解
        int tmp = 0;
        for (int i = 0; i < nums.size(); ++i)
        {
            tmp = cur;//临时存放上一个(i-1时)当前的最优解
            cur = max(nums[i] + pre, cur);//当前最优解
            pre = tmp;//前一个最优解
        }

        return cur;
    }
};

void TEST()
{
    Solution sol;
    vector<int> nums{ 5,1,3,5,2,3,4,6,7 };
    cout << sol.rob1(nums) << endl;
}

int main()
{
    TEST();

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值