• [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];
        }
    };
  • 相关阅读:
    一个完整的移动端项目的构建步骤——框架搭构1
    简单日历,纯js
    javascript语句语义大全(7)
    微软笔试Highway问题解析
    中国电信翼支付2014编程大赛决赛
    海岛问题
    大数计算
    Dijkstra算法
    Android测试之Keycode
    字符串解析
  • 原文地址:https://www.cnblogs.com/zmj97/p/7891440.html
Copyright © 2020-2023  润新知