LeetCode -- 198. House Robber

来源:互联网 发布:lol网络关注 编辑:程序博客网 时间:2024/06/05 17:43

题目:

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.


思路:
这道题是一个动态规划题,既然是动态规划,那么就得找到状态转移方程,这道题本质是求不相邻数组元素的最大组合问题,考虑抢劫到第i 家时,抢到的总钱数dist[i],第i家抢与不抢只与i-1是否被抢有关。所以:
dist[i]=max(dist[i1],dist[i2]+nums[i]),i>2
初始时:dist[0]=nums[0]dist[1]=max(nums[0],nums[1])
此时问题就被完美解决了。


C++实现:

class Solution {public:    int rob(vector<int>& nums) {        if(nums.size()==0)            return 0;        if(nums.size()==1)            return nums[0];        vector<int> dist(nums.size(), 0);        dist[0] = nums[0];        dist[1] = max(nums[0], nums[1]);        for(int i=2; i<nums.size(); ++i){            dist[i] = max(dist[i-1], dist[i-2]+nums[i]);        }        return dist[nums.size()-1];    }};
原创粉丝点击