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 };
  • 相关阅读:
    Js通用验证
    C#实现马尔科夫模型例子
    C# 生成pdf文件客户端下载
    Js跨一级域名同步cookie
    C#数据库连接池 MySql SqlServer
    关于Oracle row_number() over()的简单使用
    开发中mybatis的一些常见问题记录
    Java通过图片url地址获取图片base64位字符串的两种方式
    基于apache httpclient的常用接口调用方法
    通过jcrop和canvas的画布功能完成对图片的截图功能与视频的截图功能实现
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278230.html
Copyright © 2011-2022 走看看