class Solution {
public:
int rob(vector<int>& nums) {
const int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
if (n == 2) return max(nums[0], nums[1]);
vector<int> f(n, 0);
f[0] = nums[0];
f[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; ++i)
f[i] = max(f[i2] + nums[i], f[i1]);
return f[n1];
}
};
C++,My solution,DP


you can save some space by rotating your cache.
class Solution { public: int rob(vector<int> &nums) { int n = nums.size(); if (n == 0) { return 0; } else if (n == 1) { return nums[0]; } int dp[2] = {nums[0], std::max(nums[0], nums[1])}; for (int i = 2; i < n; ++i) { dp[i % 2] = std::max(nums[i] + dp[(i  2) % 2], dp[(i  1) % 2]); } return dp[(n  1) % 2]; } };

said in C++,My solution,DP:
if (n == 2) return max(nums[0], nums[1]);
Nice solution, This line is not needed : )