[leetcode]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个数字要不要取时,所要判别的是当前i-1个数的最大组合状态value和去除第i-1个数(i-2)的最大组合tmpvalue的值(为什么要保存之前的最大状态?这样可以保证加上第i个数时都不相邻),即判断max(value, tmpvalue + nums[i])。因此整个过程中保存两个变量即可。

注:可能会对上述递推关系产生疑问,是否存在如下可能性,value并不含num[i-1]?结论是,在这种情况下value等同于tmpvalue,因此前者更大。代码如下:

class Solution {
    public int rob(int[] nums) {
        if(nums.length == 0) return 0;
        if(nums.length == 1) return nums[0];
        if(nums.length == 2) 
            return Math.max(nums[0],nums[1]);
        int value = Math.max(nums[0],nums[1]);
        int tmpvalue = nums[0];
        int i, tmp;
        for(i = 2; i < nums.length; i++){
            if(tmpvalue + nums[i] > value){
                 tmp = value;
                 value = tmpvalue + nums[i];
                 tmpvalue = tmp;
             }else{
                  tmpvalue = value;
             }
         }
        return value;
    }
}

题目链接:https://leetcode.com/problems/house-robber/

你可能感兴趣的:(LeetCode,dp)