House Robber 动态规划

来源:互联网 发布:股票交易软件 编辑:程序博客网 时间:2024/04/29 20:17

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 tonightwithout alerting the police.

class Solution {public://在某个数组里面找一个序列, 序列里面的每一个元素都不能相邻,然后求其最大和//当前可以选择偷和不偷,dp[i]=max(dp[i-1],num[i]+dp[i-2])不偷就是dp[i-1],偷就是dp[i-2]+num[i]    int rob(vector<int>& nums) {                int len=nums.size();        if(len==0)            return 0;        else if(len==1)            return nums[0];        int *dp=new int[len];        dp[0]=nums[0];        dp[1]=max(nums[0],nums[1]);                for(int i=2;i<len;i++){            dp[i]=max(dp[i-1],dp[i-2]+nums[i]);        }        return dp[len-1];    }};

0 0
原创粉丝点击