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.
题意:
抢劫,如果抢了相邻的两家,就会触动报警器,在不触动报警器的情况下,计算能抢到的最大的钱的数目。
即求数组中部相邻数字的最大和
题解
动态规划
dp[i] : 抢劫前i家,能获得的最大财富
决策 : 第i家抢不抢
- 第i家抢,则dp[i]=num[i]+dp[i-2]
- 第i家不抢,则dp[i]=dp[i-1]
状态方程:dp[i]=max(num[i]+dp[i-2],dp[i-1])
1 | class Solution { |