[198] House Robber

1. 题目描述

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.

你是一个非常专业的小偷,一条街上有一排房间,每个房间中有一些钱,如果偷盗相邻的房间会报警,求得最佳偷盗方案下偷到的资金数量。

2. 解题思路

使用动态规划的思路,当走到每个房子的时候都有两种选择方案,抢还有不抢。
不抢:最大结果为走到前一个房子所获得的资金的最大值。
抢:最大结果为前一个房子不抢时的最大值加上当前房子的金钱数。

3. Code

// Code1:使用两个数组保存之前的最优解
public class Solution {
    public int rob(int[] nums) {
        // 使用两个数组记录当前偷了和没偷得最大值
        if(nums.length == 0) return 0;
        else if(nums.length == 1) return nums[0];
        int houseNum = nums.length;
        int[] rob = new int[houseNum];
        int[] unrob = new int[houseNum];
        // 对第一间房偷和不偷赋值
        rob[0] = nums[0];
        unrob[0] = 0;
        for(int i = 1; i < houseNum; ++i)
        {
            // 偷当前房子时的最大值为前一个房子没偷得最大值+当前屋子金钱值
            rob[i] = unrob[i-1] + nums[i];
            // 不偷当前屋子的最大值为前一个房子偷或不偷中值比较大的一个
            unrob[i] = Math.max(rob[i-1], unrob[i-1]);
        }
        return Math.max(rob[houseNum-1], unrob[houseNum-1]);
    }
}
// Code2:对于Code1的优化,使用两个变量保存前一个的最优解
public class Solution {
    public int rob(int[] nums) {
        // 使用两个数组记录当前偷了和没偷得最大值
        if(nums.length == 0) return 0;
        else if(nums.length == 1) return nums[0];
        int tempRob = 0;
        int tempUnrob = 0;
        int rob = 0;
        int unrob = 0;
        // 对第一间房偷和不偷赋值
        tempRob = nums[0];
        tempUnrob = 0;
        for(int i = 1; i < nums.length; ++i)
        {
            // 只需要保存走到前一个房子偷或不偷所产生的最大值即可
            rob = tempUnrob + nums[i];
            unrob = Math.max(tempRob, tempUnrob);
            tempRob = rob;
            tempUnrob = unrob;
        }
        return Math.max(rob, unrob);
    }
}
发布了79 篇原创文章 · 获赞 58 · 访问量 15万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章