198. House Robber

来源:互联网 发布:编程好看的字体 编辑:程序博客网 时间:2024/06/08 01:07

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.

简单来说,即从数组中选出两两不相邻的数,使和最大。


思路

设T(k)为第k晚能得到最大的总钱数。

  1. 昨晚休息。今晚得到的最大总钱数=前晚得到的最大总钱数+今晚得到的钱数。
  2. 今晚休息。今晚得到的最大总钱数=昨晚得到的最大总钱数。

即得到式子:T(k)=max(T(k-2)+nums(k), T(k-1))


代码:

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

时间复杂度:遍历一遍数组与比较操作需 O(n)
运行时间:0ms

0 0
原创粉丝点击