第十五周LeetCode

来源:互联网 发布:epson机器人编程 编辑:程序博客网 时间:2024/06/06 04:37

题目
House Robber
难度 Easy

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]表示的是当前位置抢到的最多钱之和,因为不能抢相邻的两家,因此要么抢当前这一家(则抢到的钱为前前家位置抢到的最大数目加上当前这一家的钱),要么抢前一家(dp[i-1])。因此dp[i]=max(dp[i-2]+nums[i],dp[i-1])。由状态转移方程可以看出需要初始化dp[0]和dp[1],dp[0]为nums[0],dp[1]位max(nums[0],nums[1])。最后求得dp[nums.size()-1]即为所求。

实现代码

int rob(vector<int>& nums) {        //有人家可以抢        if (nums.size() > 0) {            vector<int> dp(nums.size(),0);            dp[0] = nums[0];            if (nums.size()>1) dp[1] = max(nums[0],nums[1]);            for (int i = 2; i < nums.size(); i++) {                dp[i] = max(dp[i-2]+nums[i],dp[i-1]);            }            return dp[nums.size()-1];        // 没有钱可以抢        } else {            return 0;        }    }
原创粉丝点击