每周LeetCode算法题(七): 题目: 198. House Robber

每周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.

解法分析

题目的要求是,给定n间连续排列的房子,每间房子有一定数量的财物,作为一名小偷,要在不能同时选定相邻的两间房子下手的情况下,偷到最多数量的财物。

思路是,每次决定第i间房子该不该选择时,先考虑第i-2间房子和第i-1间房子。如果同时选择了第i间房子和第i-2间房子,那么第i-1间房子就不能选择。那么是否要选择第i间房子,取决于这样是否会得到更大的收益。若第i间房子+第i-2间房子的收益大于第i-1间房子,那么第i次的选择中最大的收益就是第i间房子+第i-2间房子的收益。否则,将不不选择第i间房子,而这次的选择的收益沿用上一次的收益,即选择第i-1间房子得到的收益。

当判断到最后,第n-1次的收益和第n-2次的收益中的最大者便是最终所求的最大收益。

C++代码

class Solution {
public:
    int rob(vector<int>& nums) {
        int a = 0;
        int b = 0;
        for (int i = 0; i < nums.size(); i++) {
            int tmp = (a + nums[i] > b)? (a + nums[i]): b;
            a = b;
            b = tmp;
        }
        return (a > b)? a: b;
    }
};

类似题目

213. House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

这题只是多了一个条件,第0间房子和第n-1间房子是相邻的,即这两间房子不能都选。于是问题分成了两部分,一个是第0到n-2间房子的选择,一个是第1到n-1间房子的选择。

class Solution {
public:
    int rob(vector<int>& nums) {
        int c1 = 0, c2 = 0;
        int a = 0;
        int b = 0;
        if (nums.size() == 0) {
            return 0;
        } else if (nums.size() == 1) {
            return nums[0];
        }
        for (int i = 0; i < nums.size() - 1; i++) {
            int tmp = (a + nums[i] > b)? (a + nums[i]): b;
            a = b;
            b = tmp;
        }
        c1 = (a > b)? a: b;
        a = 0;
        b = 0;
        for (int i = 1; i < nums.size(); i++) {
            int tmp = (a + nums[i] > b)? (a + nums[i]): b;
            a = b;
            b = tmp;
        }
        c2 = (a > b)? a: b;
        return (c1 > c2)? c1: c2;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值