java 动态规划问题(2)

来源:互联网 发布:dreamweaver调试js 编辑:程序博客网 时间:2024/04/30 12:40

题目:
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.

解题思路:

这是一个典型的动态规划问题:

假设小偷到第i家时所偷的金钱最大额为temp[i],则有如下关系:

temp[i] = max(temp[i-1],temp[i-2]+nums[i]);

算法如下:

public class Solution {    public int rob(int[] nums) {        if(nums==null||nums.length==0) return 0;        if(nums.length==1) return nums[0];        if(nums.length==2) return max(nums[0],nums[1]);        int[] temp = new int[nums.length];        temp[0] = nums[0];        temp[1] = max(nums[0],nums[1]);        for(int i=2;i<temp.length;i++){            temp[i] = max(temp[i-1],temp[i-2]+nums[i]);        }        return temp[temp.length-1];    }    public int max(int a,int b){        return a>b?a:b;    }}
0 0
原创粉丝点击