leetCode#198. House Robber

来源:互联网 发布:防网络诈骗图片 编辑:程序博客网 时间:2024/06/16 06:10

Description

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.

Code

class Solution(object):    def rob(self, nums):        """        :type nums: List[int]        :rtype: int        """        if len(nums) == 0:            return 0        if len(nums) == 1:            return nums[0]        if len(nums) == 2:            return max(nums[0], nums[1])        if len(nums) == 3:            return max(nums[1], nums[0] + nums[2])        return max(nums[0] + self.rob(nums[2:]), nums[1] + self.rob(nums[3:]))

这个没有通过时间检测,不过思路很清晰了,就是遍历。
别人的代码:

#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<n; i++)    {        if (i%2==0)        {            a = max(a+num[i], b);        }        else        {            b = max(a, b+num[i]);        }    }    return max(a, b);}
class Solution {public:    int rob(vector<int>& nums) {         int n = nums.size(), pre = 0, cur = 0;        for (int i = 0; i < n; i++) {            int temp = max(pre + nums[i], cur);            pre = cur;            cur = temp;        }        return cur;    }};

f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )
执行的就是这个公式。感觉得死记了,自己并没有很好的理解这题的思路。

原创粉丝点击