关闭

leetcode 198:House Robber

157人阅读 评论(0) 收藏 举报
分类:

题目:
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个房屋的行为后最大获得的现金”,记为d[i],行为在这里就是偷或不偷。则状态转移方程可以为:d[i]=max{d[i-2]+nums[i],d[i-1]}
代码:

public class HouseRobber {
    public int rob(int[] nums){
        int len=nums.length;
        int odd = 0,even=0;
        for(int i=0;i<len;i++){
            if(i%2==0){
                odd=Math.max(odd+nums[i], even);
            }else{
                even=Math.max(even+nums[i],odd);
            }
        }
        return Math.max(odd, even);
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8501次
    • 积分:400
    • 等级:
    • 排名:千里之外
    • 原创:33篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条