文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. 问题描述
ou 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.
2. 求解
方法一递归法
递归法如下图所示,从第0家开始,偷与不偷有两种情况,如果偷了则从第2家开始重复此过程,如果没偷,从第1家开始重复此过程,直至结束。
1 | public class Solution { |
Leetcode运行超时,说明存在优化空间。
方法二递归法+缓存
从图中可以看出,上述过程中会有重复的计算,例如从第二家开始偷的情况计算了两次,我们可以用一个HashMap将计算过的数据保存起来,去掉冗余计算。
1 | public class Solution { |
方法三:非递归
将递归改造成非递归。
1 | public class Solution { |
方法四:HashMap变为数组
为了节省空间,可以将HashMap变为数组,代码也可以进一步优化,去掉三目运算符。
1 | public class Solution { |