CoolSummer

数据可视化

LeetCode: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.

思路:

动态规划,设置maxn[i]表示到第i个房子位置,最大收益。

递推关系为maxn[i] = max(maxn[i-2]+nums[i], maxn[i-1]);


C++代码:

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


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014744118/article/details/49913521
文章标签: leetcode c++
个人分类: LeetCode
上一篇LeetCode:Symmetric Tree
下一篇LeetCode:Min Stack
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭