zoukankan      html  css  js  c++  java
  • [leetcode] 198. 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.


    若抢了最后一家,则倒数第二家一定没抢,若没抢最后一家,则相当于只抢前几家。

    因此可得:re[n] = max(money[n] + re[n-2], re[n-1])

    用递归的话会超时,因此用循环,其实因为只跟n-1和n-2有关可以只存两个,因为都比较简单这里就不给出了。

    我的代码:

    class Solution {
    public:
        int rob(vector<int>& nums) {
            int len = nums.size();
            if (len == 0) return 0;
            if (len == 1) return nums[0];
            if (len == 2) return max(nums[0], nums[1]);
            vector<int> re;
            re.push_back(nums[0]);
            re.push_back(max(nums[0], nums[1]));
            for (int i = 2; i < len; i++) {
                re.push_back(max(re[i-1], nums[i] + re[i-2]));
            }
            return re[len-1];
        }
    };
  • 相关阅读:
    springMVC静态资源
    MyBatis Generator
    使用springMVC时的web.xml配置文件
    Semaphore
    spring注解驱动--组件注册
    第1章 初始Docker容器
    docker面试整理
    第5章 运输层
    验证码
    带进度条的上传
  • 原文地址:https://www.cnblogs.com/zmj97/p/7891440.html
Copyright © 2011-2022 走看看