# House Robber

#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
int rob(vector<int>& nums) {
int hasFinal, exceptFinal;

if(nums.size() == 0)
return 0;

if(nums.size() == 1)
return nums[0];

if(nums.size() == 2) {
if(nums[0] > nums[1])
return nums[0];
else
return nums[1];
}

int tmp1, tmp2;
int maxNM1 = max(nums[0], nums[1]);
int maxNM2 = nums[0];
int maxN;
for(int i = 3; i <= nums.size(); i++) {
if(i != 3) {
maxNM2 = maxNM1;
maxNM1 = maxN;
}

tmp1 = maxNM2 + nums[i - 1];
tmp2 = maxNM1;
maxN = max(tmp1, tmp2);
}

return maxN;

//recursive version
/*int hasFinal, exceptFinal;

if(nums.size() == 0)
return 0;

if(nums.size() == 1)
return nums[0];

if(nums.size() == 2) {
if(nums[0] > nums[1])
return nums[0];
else
return nums[1];
}

if(nums.size() == 3) {
hasFinal = nums[0] + nums[2];
if(nums[0] > nums[1])
exceptFinal = nums[0];
else
exceptFinal = nums[1];
if(hasFinal > exceptFinal)
return hasFinal;
else
return exceptFinal;
}

//int hasFinal, exceptFinal;
vector<int> arr1(nums.begin(), nums.end() - 2);
vector<int> arr2(nums.begin(), nums.end() - 1);
hasFinal = rob(arr1) + *(nums.end() - 1);
exceptFinal = rob(arr2);
if(hasFinal > exceptFinal)
return hasFinal;
else
return exceptFinal;*/
}
};

int main() {
vector<int> arr;
arr.push_back(5);arr.push_back(4);arr.push_back(1);arr.push_back(6);
arr.push_back(57);arr.push_back(24);arr.push_back(48);arr.push_back(12);
Solution solution;
cout << solution.rob(arr) << endl;
getchar();
}
• 本文已收录于以下专栏：

## 337. House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this a...

## House Robber III

c++/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *l...

## <LeetCode OJ> (198 / 213) House Robber（I / II）

House Robber My Submissions Question Total Accepted: 45702 Total Submissions: 142460 Difficulty:...

## LeetCode-难题集之House_Robber系列

• ww2041
• 2016年07月26日 10:25
• 97

## LeetCode 337. House Robber III

• isNoel
• 2016年12月22日 18:49
• 167

## leetcode 337:House Robber III

leetcode 337：House Robber III。leetcode新题，递归的动态规划

## DP (9) -- Maximal Square, Maximal Rectangle，House Robber II

Maximal Square, Maximal Rectangle, House Robber II
• dwt0317
• 2017年01月12日 16:34
• 60

## LeetCode House Robber题解

House_Robber 题目如下所示 You are a professional robber planning to rob houses along a street. Each house...
• qisong3
• 2015年04月10日 10:38
• 288

## DP (1) -- Range Sum Query - Immutable, House Robber, Climbing Stairs

Range Sum Query - Immutable，House Robber
• dwt0317
• 2017年01月04日 20:27
• 103

举报原因： 您举报文章：House Robber 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)