- 198.打家劫舍
```cpp
class Solution {
public:
int rob(vector
if (nums.size() == 1) return nums[0];
vector
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < nums.size(); i++) {
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[nums.size() - 1];
}
};
```
- 213.打家劫舍II
```cpp
class Solution {
public:
int robRange(vector
if (start == end) return nums[start];
vector
dp[start] = nums[start];
dp[start + 1] = max(nums[start], nums[start + 1]);
for (int i = start + 2; i <= end; i++) {
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[end];
}
int rob(vector
if (nums.size() == 1) return nums[0];
int result1 = robRange(nums, 0, nums.size() - 2);
int result2 = robRange(nums, 1, nums.size() - 1);
return max(result1, result2);
}
};
```
- 337.打家劫舍III
```cpp
class Solution {
public:
// 0偷 1不偷
vector
if (!cur) return {0, 0};
vector
vector
// 偷cur
int val1 = cur->val + left[1] + right[1];
// 不偷cur
int val2 = max(left[0], left[1]) + max(right[0], right[1]);
return {val1, val2};
}
int rob(TreeNode* root) {
vector
return max(result[0], result[1]);
}
};
```