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.

思路:

这个问题一开始我是觉得很像是递归解决的,于是采用最直接的方法,每求一个节点 k,都考虑求 k+1,k+2 两者之间最大值,以此类推。于是有代码一。

但是提交后发现是 Time Limit Exceeded,看来不能偷懒做少事儿啊。

上面方法相当于是树结构的由高层到底层,抽象递归;于是又想到从底层到高层,如当前计算节点 k 的目标值,只使用排列在自己之前的信息 0~k-1 节点,计算最佳总和并记录;然后后面节点 k+1,可以在 k-1,k-2 之间选择最佳方案。有点 Adaptive 的感觉。如代码二。

代码:

//code I
/* Time Limit Exceeded Solution*/
class Solution {
public:
    int rob(vector<int>& nums) {
        return rob_recursive(nums, 0);
    }

    //recusively cope with the subarray
    int rob_recursive(vector<int>& nums, unsigned head)
    {
        if (nums.size() > head) 
        {
            int local_sum_1 = nums[head] + rob_recursive(nums, head + 2);  //skip the head+1
            if (nums.size() > head + 1)
            {
                int local_sum_2 = nums[head + 1] + rob_recursive(nums, head + 3); //skip the head+2

                if (local_sum_1 < local_sum_2)
                    return local_sum_2;
            }
            return local_sum_1;
        }
        return 0;
    }
};
//code II
class Solution {
public:

    int rob(vector<int>& nums) {
        vector<int> sum_record;
        unsigned length = nums.size();
        if (length == 0) return 0;
        if (length == 1) return *nums.begin();
        if (length == 2) return nums[0] > nums[1] ? nums[0] : nums[1];
        if (length == 3)
        {

            return nums[0]+nums[2] > nums[1] ? nums[0] + nums[2] : nums[1];

        }
        sum_record.push_back(nums[0]);
        sum_record.push_back(nums[1]);
        sum_record.push_back(nums[0]+nums[2]);

        for (int i = 3; i < length;i++)
        {   
            int pre = nums[i] + sum_record[i - 2];      //skip the i-1
            int pre_pre = nums[i] + sum_record[i - 3];  //skip the i-2
            sum_record.push_back(pre > pre_pre ? pre : pre_pre);
        }
        return sum_record[length - 1] > sum_record[length - 2] ? sum_record[length - 1] : sum_record[length - 2];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值