198. House Robber

来源:互联网 发布:新浪微博推广淘宝产品 编辑:程序博客网 时间:2024/06/07 22:24

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.

題意:一個小偷要在一條街進行偷竊,而每棟房子所藏的錢都不一樣,而偷竊兩棟相連接的房子則會觸動警鈴(不能偷竊兩棟相鄰的房子),而小偷的得手的金額最大為多少?

 這題可以用動態規劃來解題,遞歸式如下:
    results[0] = nums[0]
    results[0] = max(nums[0], nums[1])
    results[i] = max(results[i - 1], results[i - 2] + nums[i])    if  i >= 2
                       往前第一個        往前第二個  +  目前


    例如:
    step      0 1 2 3 4
    ====================
    nums    = 1 2 3 4 5
    results = 1 2 4 6 9

package LeetCode.Easy;public class HouseRobber {    /*    這題可以用動態規劃來解題,遞歸式如下:    results[0] = nums[0]    results[0] = max(nums[0], nums[1])    results[i] = max(results[i - 1], results[i - 2] + nums[i])    if  i >= 2                       往前第一個        往前第二個  +  目前    例如:    step      0 1 2 3 4    ====================    nums    = 1 2 3 4 5    results = 1 2 4 6 9        */    public int rob(int[] nums) {        if(nums == null || nums.length == 0) {            return 0;        }                int n = nums.length;                if(n == 1)            return nums[0];                //存儲結果        int[] results = new int[n + 1];                //定義初始狀態        results[0] = nums[0];        results[1] = Math.max(nums[0], nums[1]);                for(int i = 2; i < n; i ++) {            int rob_house_1 = results[i - 2] + nums[i]; //搶前面第二個+目前這個            int rob_house_2 = results[i - 1]; //搶前面一個            results[i] = Math.max(rob_house_1, rob_house_2); //比較兩者誰較大        }                return results[n - 1];    }}


原创粉丝点击