博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: House Robber
阅读量:4601 次
发布时间:2019-06-09

本文共 1509 字,大约阅读时间需要 5 分钟。

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:我们维护一个一位数组dp,其中dp[i]表示到达 index = i 位置时不相邻数能形成的最大和,i不一定是最后一个rob的房子

dp[0] = num[0];

dp[i] = max(dp[i-1], i>=2? dp[i-2]+num[i] : num[i]);

时间复杂度: O(N), 空间复杂度: O(N) ->O(1)

1 public class Solution { 2     public int rob(int[] num) { 3         if (num==null || num.length==0) return 0; 4         int[] res = new int[num.length]; 5         res[0] = num[0]; 6         for (int i=1; i
=2? res[i-2]+num[i] : num[i]); 8 } 9 return res[num.length-1];10 }11 }

 

第一遍做法:

DP,一维数组dp[i] 表示 以 index = i 房子作为最后一个rob的房子的最大抢劫金额

dp[0] = num[0];

dp[i] = max{dp[0], dp[1], ... dp[i-2]} + num[i];

最后return的是dp[0].....dp[num.length-1]中的最大值

虽然这个思路在这里略麻烦,O(N^2), 但不失为一个好思路

1 public class Solution { 2     public int rob(int[] num) { 3         if (num==null || num.length==0) return 0; 4         int[] res = new int[num.length]; 5         res[0] = num[0]; 6         if (num.length > 1) res[1] = num[1]; 7         for (int i=2; i

 

转载于:https://www.cnblogs.com/EdwardLiu/p/4418967.html

你可能感兴趣的文章
MySQL源码 数据结构array
查看>>
(文件过多时)删除目录下全部文件
查看>>
T-SQL函数总结
查看>>
python 序列:列表
查看>>
web移动端
查看>>
pythonchallenge闯关 第13题
查看>>
linux上很方便的上传下载文件工具rz和sz使用介绍
查看>>
React之特点及常见用法
查看>>
【WEB前端经验之谈】时间一年半,或沉淀、或从零开始。
查看>>
优云软件助阵GOPS·2017全球运维大会北京站
查看>>
linux 装mysql的方法和步骤
查看>>
poj3667(线段树区间合并&区间查询)
查看>>
51nod1241(连续上升子序列)
查看>>
SqlSerch 查找不到数据
查看>>
集合相关概念
查看>>
Memcache 统计分析!
查看>>
(Python第四天)字符串
查看>>
个人介绍
查看>>
使用python动态特性时,让pycharm自动补全
查看>>
MySQL数据库免安装版配置
查看>>