博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 198 House Robber
阅读量:4662 次
发布时间:2019-06-09

本文共 1914 字,大约阅读时间需要 6 分钟。

今天看了一个华为西安研究院的一个女生代码大神的总结很有感悟,下面这句话送给大家:

只有好的程序员才能写出人类可以理解的代码

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.

the objective function is basically:

dp(i) = max(dp[i-2] + num[i], dp[i-1]),

this means the current max is the max of the position i-2 plus the current num[i], or the max of the previous one i-1 (cannot including num[i] with i-1 position, otherwise it will trigger the alarm)

我的解决方案:

这里写图片描述

class Solution {public:    int rob(vector
& nums) { if(nums.empty())return 0; int length = nums.size(); vector
dp(length,0); dp[0] = nums[0]; dp[1] = max(nums[0],nums[1]); for(int i =2; i< length; ++i) { dp[i] = max(dp[i-2]+nums[i],dp[i-1]); } return dp[length-1]; }};

c语言解决方案:

#define max(a, b) ((a)>(b)?(a):(b))int rob(int num[], int n) {    int a = 0;    int b = 0;    for (int i=0; i

python解决方案:

class Solution:    # @param num, a list of integer    # @return an integer    def rob(self, num):        # DP O(n) time, O(1) space        # ik: max include house k        # ek: max exclude house k, (Note: ek is also the maximum for house 1,...,k-1)        # i[k+1]: num[k] + ek #can't include house k        # e[k+1]: max(ik, ek) # can either include house k or exclude house k        i, e = 0, 0        for n in num: #from k-1 to k            i, e = n+e, max(i,e)        return max(i,e)

转载于:https://www.cnblogs.com/wangyaning/p/7853992.html

你可能感兴趣的文章
lambda表达式树
查看>>
二次注入原理及防御
查看>>
会话记住已登录功能
查看>>
Linux内核分析——可执行程序的装载
查看>>
读《大道至简》第六章感想
查看>>
ef linq 中判断实体中是否包含某集合
查看>>
章三 链表
查看>>
函数名作为参数传递
查看>>
apt-get for ubuntu 工具简介
查看>>
数值计算算法-多项式插值算法的实现与分析
查看>>
day8-异常处理与网络编程
查看>>
Python基础-time and datetime
查看>>
shell脚本练习01
查看>>
WPF图标拾取器
查看>>
通过取父级for循环的i来理解闭包,iife,匿名函数
查看>>
HDU 3374 String Problem
查看>>
数据集
查看>>
[Leetcode] unique paths ii 独特路径
查看>>
HDU 1217 Arbitrage (Floyd + SPFA判环)
查看>>
IntelliJ idea学习资源
查看>>