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[i] = max(dp[i - 1], dp[i - 2] + nums[i], dp[i-3] + nums[i], .....)

显然上面的表达式有多余的

dp[i - 2] + nums[i] > dp[j] + nums[i](对于任意的 0<=j<i-2)
因为dp[i - 2] = max(dp[i - 3], dp[i - 4] + nums[i-2]....)的
也就是说dp[i]只和dp[i - 1]与dp[i - 2]有关
class Solution {
public:
    int rob(vector<int>& nums) {
        //cur记录前一个节点,pre记录cur的前一个节点
        int pre = 0, cur = 0;

        for(int i = 0; i < nums.size(); i++){
            int temp = max(pre + nums[i], cur);

            pre = cur;
            cur = temp;
        }

        return max(pre, cur);
    }
};

还可以分奇数偶数来做

class Solution {
public:
    int rob(vector<int>& nums) {
        int odd = 0, even = 0;

        for(int i = 0; i < nums.size(); ++i){
            //i%2 == 0为偶数even
            if( i % 2 == 0 )
                even = max(odd, even + nums[i]);
            //奇数
            else
                odd = max(even, odd + nums[i]);

        }
        return max(odd, even);
    }
};

213.House Robber II

Note: This is an extension of House Robber.

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.

此处构成了环,这就导致了不一定是从nums[0]开始,也有可能从num[1]开始;
class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() == 0)
            return 0;
        if(nums.size() == 1)
            return nums[0];
        int n = nums.size() - 1;
        return max(robber(nums, 0, n - 1), robber(nums, 1, n));
    }
private:
    int robber(vector<int>& arr, int l, int r){
        int pre = 0, cur = 0;

        for(int i = l; i <= r; i++){
            int temp = max(pre + arr[i], cur);
            pre = cur;
            cur = temp;
        }
        return cur;
    }
};

results matching ""

    No results matching ""