zoukankan      html  css  js  c++  java
  • (easy)LeetCode 198.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.

    Credits:
    Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

    方法一:递归(超时)

    代码如下:

    public class Solution {
        public int rob(int[] nums) {
           int m1= robWay(nums,0);
           int m2= robWay(nums,1);
           int max=m1>m2?m1:m2;
           return max;
        }
        public int robWay(int[] nums,int begin){
            int len=nums.length;
            if(begin==len-1) return nums[begin];
            if(begin>len-1) return 0;
            int m1=nums[begin]+robWay(nums,begin+2);
            int m2=nums[begin]+robWay(nums,begin+3);
            int max=m1>m2?m1:m2;
            return max;
           
        }
    }

    运行结果:

    方法2:动态规划

    针对第n个房间,要么偷,要么不偷。

    偷:take=noTake+nums[i];

    不偷:noTake=maxProfile;

    maxProfile=Math.max(take,noTake);

    代码如下:

    public class Solution {
        public int rob(int[] nums) {
           int take=0;

           int noTake=0;

           int maxProfit=0;

           for(int i=0;i<nums.length;i++){

                 take=nums[i]+noTake;

                 noTake=maxProfit;

                 maxProfit=Math.max(take,noTake);

            }

            return maxProfit;
        }
       
    }

    运行结果:

  • 相关阅读:
    记录一下自己的洛谷的题解
    初学java 学生管理系统——v0002版本
    初学java 学生管理系统——v0001版本
    Redis守护进程作用+数据类型
    java实现发送短信验证码
    Kali入侵入门版笔记!!!
    2020实现ssh公网外联和外网远程穿透以及内网穿透防火墙
    监控键盘和鼠标记录内容和截屏,更新版本2.0,增加了Linux服务端!!!
    Git管理软件开发项目入门版
    2020年Windows下开机自动执行最强
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/4680069.html
Copyright © 2011-2022 走看看