zoukankan      html  css  js  c++  java
  • leetcode198:打家劫舍

    你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。

    给定一个代表每个房屋存放金额的非负整数数组,计算你不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。

    示例 1:

    输入:[1,2,3,1]
    输出:4
    解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
    偷窃到的最高金额 = 1 + 3 = 4 。

    ==============================================Python=============================================

    class Solution:
        def rob(self, nums: List[int]) -> int:
            yes, no = 0, 0
            for num in nums:
                yes, no = no + num, max(no, yes)
            return max(yes, no)

    =======================================================Go============================================================

    func rob(nums []int) int {
        if len(nums) < 1 {
            return 0
        }
        if len(nums) == 1 {
            return nums[0]
        }
        if len(nums) == 2 {
            return max(nums[0], nums[1])
        }
        nums[1] = max(nums[0], nums[1])
        for i := 2; i < len(nums); i++ {
            nums[i] = max(nums[i-2] + nums[i], nums[i-1])
        }
        return nums[len(nums) - 1]
    }
    func max(a, b int) int {
        if a > b {
            return a
        }
        return b
    }
  • 相关阅读:
    MySql 学习之 一条更新sql的执行过程
    MySql 学习之 一条查询sql的执行过程
    VUE基本介绍
    ESMAScript6基本介绍
    npm
    tensorflow2.0 评估函数
    网页引入mathjax,latex
    Veno File Manager
    tensorflow 测量工具,与自定义训练
    tensorflow自定义网络结构
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13512465.html
Copyright © 2011-2022 走看看