zoukankan      html  css  js  c++  java
  • 198. House Robber

    #week7

    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.

    Credits:
    Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

    分析:

    动态规划类型

    f[0,i]:从0到第i户,偷了第i户的最大结果

    f[1,i]:从0到第i户,不偷第i户的最大结果

    状态转移:

    f[0][i] = max(f[1][i-1], f[0][i-1]);
    f[1][i] = f[0][i-1] + nums[i];

    初始化:

    f[0][0] = 0;
    f[1][0] = nums[0];

    题解:

     1 class Solution {
     2 public:
     3     int max(int a, int b) {
     4         if (a > b) return a;
     5         return b;
     6     }
     7     int rob(vector<int>& nums) {
     8         int size = nums.size();
     9         if (size == 0) return 0;
    10         int** f;
    11         f = new int*[2];
    12         f[0] = new int[size];
    13         f[1] = new int[size];
    14         f[0][0] = 0;
    15         f[1][0] = nums[0];
    16         for (int i = 1; i < size; i++) {
    17             f[0][i] = max(f[1][i-1], f[0][i-1]);
    18             f[1][i] = f[0][i-1] + nums[i];
    19         }
    20         return max(f[0][size-1], f[1][size-1]);
    21     }
    22 };

    看了其他人答案,化为一维也是可以的:

     1 class Solution {
     2 public:
     3     int rob(vector<int>& nums) {
     4         const int n = nums.size();
     5         if (n == 0) return 0;
     6         if (n == 1) return nums[0];
     7         if (n == 2) return max(nums[0], nums[1]);
     8         vector<int> f(n, 0);
     9         f[0] = nums[0];
    10         f[1] = max(nums[0], nums[1]);
    11         for (int i = 2; i < n; ++i)
    12             f[i] = max(f[i-2] + nums[i], f[i-1]);
    13         return f[n-1];
    14     }
    15 };
  • 相关阅读:
    jenkins1—docker快速搭建jenkins环境
    UPC-6616 Small Multiple(BFS广搜&双向队列)
    UPC-5502 打地鼠游戏(贪心&优先队列)
    UPC-5500 经营与开发(贪心&逆推)
    NBUT
    UPC-6690 Transit Tree Path(树上最短路径SPFA)
    UPC-6359 售票(字典树)
    UPC-6358 庭师的利刃(两数与运算最大值)
    HDU-6308 Time Zone(时区转换)
    欧拉函数模板及拓展
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278230.html
Copyright © 2011-2022 走看看