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.

    题解:

      对于求最大,最小类问题,应该联想到是否能用DP思想,问题可以具体为给定一个数组,取出一系列的数使和最大,约束就是取出的数不能相邻。状态方程:

    dp[n] = max(dp[n-1], dp[n-2] + array[n]);

    Solution 1

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

      可以看出Solution1中数组只需要维护一次,那么我们就可以用两个变量代表前一个最大值和前两个的最大值,

    Solution 2

    class Solution {
    publicint rob(vector<int> &money) {
            int n1=0, n2=0;
            int n = money.size();
            for (int i=0; i<n; i++){
                int now = max(n1, n2 + money[i]);
                n2 = n1;
                n1 = now;
            }
            return n1;
        }
    };

      还有一种类似比较容易理解的方法

    Solution 3

    class Solution {
    public:
        int rob(vector<int> &money) {
            int n1 = 0, n2 = 0, n = money.size();
            for (int i=0; i<n; i++) {
                if (i%2==0) n1 = max(n1+money[i], n2);
                else n2 = max(n1, n2+money[i]);
            }
            return max(n1, n2);
        }
    };
  • 相关阅读:
    动态规划 01背包问题
    日常水题 蓝桥杯基础练习VIP-字符串对比
    本博客导航
    2019 ICPC 南昌 (C E G L)
    [模板]线段树
    [模板]手写双端队列(或普通队列)
    2019 ICPC Asia Yinchuan Regional (G, H)
    与超级源点与超级汇点相关的两题POJ 1062, HDU 4725
    [模板]链式向前星
    [总结]关于反向建图
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6748367.html
Copyright © 2011-2022 走看看