LeetCode198.打家劫舍
题目链接:198. 打家劫舍 - 力扣(LeetCode)
思路:
class Solution {
public:int rob(vector<int>& nums) {if(nums.size() == 0) return 0;if(nums.size() == 1) return nums[0];vector<int> dp(nums.size());//最多偷窃金额dp[0] = nums[0];//初始化dp[1] = max(nums[0], nums[1]);for(int i = 2; i < nums.size(); i++) {dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);//前一个为偷i房间,后一个为不偷i}return dp[nums.size() - 1];}
};
LeetCode213.打家劫舍II
题目链接:213. 打家劫舍 II - 力扣(LeetCode)
思路:
class Solution {
public:int rob(vector<int>& nums) {if(nums.size() == 0) return 0;if(nums.size() == 1) return nums[0];int result1 = robrange(nums, 1, nums.size() - 1);//不考虑首int result2 = robrange(nums, 0, nums.size() - 2);//不考虑尾return max(result1, result2);}int robrange(vector<int>& nums, int start, int end) {if(end == start) return nums[start];vector<int> dp(nums.size());//首尾相邻偷最多钱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 - 2] + nums[i], dp[i - 1]);//递推}return dp[end];}
};
LeetCode 337.打家劫舍III
题目链接:337. 打家劫舍 III - 力扣(LeetCode)
思路:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:int rob(TreeNode* root) {vector<int> result = robTree(root);return max(result[0], result[1]);}//长度为二的数组,0:不偷,1:偷vector<int> robTree(TreeNode* cur) {if(cur == NULL) return vector<int> {0, 0};vector<int> left = robTree(cur->left);vector<int> right = robTree(cur->right);//偷cur不能偷左右节点int val1 = cur->val + left[0] + right[0];//不偷cur那么可以偷也可以不偷左右节点,比大小看谁大取谁int val2 = max(left[0], left[1]) + max(right[0], right[1]);return {val2, val1};}
};