• [leet code 198]House Robber


    1 题目

    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.

    Hide Tags
     Dynamic Programming
     
    2 分析
     
    提示是动态规划,也就是要先写好递推方程。好吧,我自己想了半天想不出来,总是有问题。看了别人的代码之后就想明白了。递推方程是:cache[i] = Max[cache[i-1] + num[i],cache[i-1]];  取前者时,肯定没有相邻的房间,而去后者,就不rob房间i,前面的rob的房间序列也是满足条件的,所以该递推方程有效。
     
    3 代码
         public int rob(int[] num) {
                int n = num.length;
                if (n < 2)
                    return n == 0 ? 0 : num[0];
                int[] cache = new int[n];
                cache[0] = num[0];
                cache[1] = num[0] > num[1] ? num[0] : num[1];
                for (int i = 2; i < n; i++) {
                    cache[i] = cache[i - 2] + num[i];
                    cache[i] = cache[i] > cache[i-1]? cache[i] : cache[i-1];
                }
                return cache[n - 1];
            
        }
  • 相关阅读:
    Alpha冲刺(8/10)
    Alpha冲刺(7/10)
    Alpha冲刺6
    Alpha冲刺5
    GIT团队实战博客
    Alpha冲刺4
    STM32和WM8960 I2S 利用DMA双缓冲音频播放和录音(二)
    STM32和WM8960 I2S 利用DMA双缓冲音频播放和录音(一)
    USART DMA双缓冲给PC发送数据和接收PC数据
    详细理解STM32F42x系列的DMA配置
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4388205.html
Copyright © 2020-2023  润新知