动态规划——198. House Robber[easy]

来源:互联网 发布:多媒体网络的应用 编辑:程序博客网 时间:2024/06/05 19:15

题目描述


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.

计算小偷一晚上偷钱的最大数额,不能连续偷相邻两家,用数组nums代表每一家的现金数。


解题思路

令re[i]表示偷到 i 时的最大数额,re[n]即为所求。小偷在 i 时有两个选择:

1、偷,说明前一家没偷,此时最大数额为re[i-2]+ nums[i]

2、不偷,说明偷了前一家,此时数额为 re[i-1]


因此 re[i] = max(re[i-1],re[i-2]+ nums[i])


代码如下


class Solution {public:    int rob(vector<int>& nums) {        if (nums.size() >= 3) {vector<int> re(nums.size(), 0);re[0] = nums[0];re[1] = re[1] = fmax(re[0], 0 + nums[1]);for (int i = 2; i < nums.size(); i++) {re[i] = fmax(re[i - 2] + nums[i], re[i - 1]);}return re[nums.size() - 1];}else if (nums.size() == 2) {return (nums[0] > nums[1]) ? nums[0] : nums[1];}else if (nums.size() == 1)return nums[0];elsereturn 0;    }};

注意考虑nums大小,以及re[0]、re[1]的初始化:

可以考虑re[-2]、re[-1]都为0,从而得出re[0],re[1]

0 0
原创粉丝点击