zoukankan      html  css  js  c++  java
  • 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数组,递推公式为:Math.Max(dp[i - 1], nums[i] + dp[i - 2]);
    1. public class Solution {
    2. public int Rob(int[] nums) {
    3. if (nums.Length == 0) {
    4. return 0;
    5. } else if (nums.Length == 1) {
    6. return nums[0];
    7. } else if (nums.Length == 2) {
    8. return Math.Max(nums[0], nums[1]);
    9. }
    10. int[] dp = new int[nums.Length];
    11. dp[0] = nums[0];
    12. dp[1] = Math.Max(nums[0], nums[1]);
    13. for (int i = 2; i < nums.Length; i++) {
    14. dp[i] = Math.Max(dp[i - 1], (nums[i] + dp[i - 2]));
    15. }
    16. return dp[nums.Length - 1];
    17. }
    18. }





  • 相关阅读:
    2020/8/8
    2020/8/7
    2020/8/6
    2020/8/5
    2020/8/4
    2020/8/3
    19,CSS 滤镜
    18 章 CSS 链接、光标、 DHTML 、缩放
    17 , CSS 区块、浮动、定位、溢出、滚动条
    16 , CSS 边框与边界
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/9cb87bc9eb8ccf32eff472196e66add4.html
Copyright © 2011-2022 走看看