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 };
  • 相关阅读:
    前端总结(设计向)
    bootstrap 样式规范总结
    angular2学习---模板学习
    angular2学习 -- 基本配置学习
    前端相关小技巧以及问题总结
    认识hasLayout——IE浏览器css bug的一大罪恶根源 转
    bug 由于浏览器缓存而引起的ajax请求并没有获取到服务器最新数据从而导致的bug
    总结 好用的工具/网站/插件
    .NET FrameWork完全卸载
    ASP.NET4.0项目部署到Win7系统的IIS上
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278230.html
Copyright © 2011-2022 走看看