198.打家劫舍
视频讲解:动态规划,偷不偷这个房间呢?| LeetCode:198.打家劫舍_哔哩哔哩_bilibili
代码随想录
class Solution {
public:int rob(vector<int>& nums) {vector<vector<int>>dp(nums.size(),vector<int>(2,0));dp[0][1]=nums[0];for (int i=1;i<nums.size();i++){dp[i][0]=max(dp[i-1][1],dp[i-1][0]);dp[i][1]=dp[i-1][0]+nums[i];}return max(dp[nums.size()-1][1],dp[nums.size()-1][0]);}
};
class Solution {
public:int rob(vector<int>& nums) {if (nums.size()==1)return nums[0];if (nums.size()==2)return max(nums[0],nums[1]);vector<int>dp(nums.size()+1,0);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
视频讲解:动态规划,房间连成环了那还偷不偷呢?| LeetCode:213.打家劫舍II_哔哩哔哩_bilibili
代码随想录
class Solution {
public:int rob(vector<int>& nums) {if (nums.size()==1)return nums[0];if (nums.size()==2)return max(nums[0],nums[1]);if (nums.size()==3)return max(nums[0],max(nums[1],nums[2]));vector<int>dp(nums.size(),0);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]);}int res1=dp[nums.size()-2];dp[1]=nums[1];dp[2]=max(nums[1],nums[2]);for (int i=3;i<nums.size();i++){dp[i]=max(dp[i-1],dp[i-2]+nums[i]);}int res2=dp[nums.size()-1];return max(res1,res2);}
};
337.打家劫舍III
视频讲解:动态规划,房间连成树了,偷不偷呢?| LeetCode:337.打家劫舍3_哔哩哔哩_bilibili
代码随想录
/*** 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:vector<int> traversal(TreeNode* root){if (!root)return {0,0};vector<int> left=traversal(root->left);vector<int> right=traversal(root->right);//表示偷了int val1=left[0]+right[0]+root->val;//表示没有偷int val2=max(left[0],left[1])+max(right[0],right[1]);return {val2,val1};}int rob(TreeNode* root) {vector<int>res=traversal(root);return max(res[0],res[1]);}
};