打家劫舍
class Solution {
public:
int rob(vector
if (nums.size() == 0) return 0;
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-2] + nums[i], dp[i-1]);
}
return dp[nums.size() - 1];
}
};
打家劫舍II
class Solution {
public:
int rob1(vector
if (nums.size() == 0) return 0;
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-2] + nums[i], dp[i-1]);
}
return dp[nums.size() - 1];
}
int rob(vector
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
vector
for(int i = 0; i < nums.size() - 1; ++i)
{
vec1.push_back(nums[i]);
}
vector
for(int i = 1; i < nums.size(); ++i)
{
vec2.push_back(nums[i]);
}
return max(rob1(vec1), rob1(vec2));
}
};
打家劫舍III
/**
-
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:
vectortraversal(TreeNode root)
{
if(root == nullptr)
{
return {0, 0};
}
vectorleft = traversal(root->left); root) {
vectorright = traversal(root->right);
int val1 = root->val + left[0] + right[0];
int val2 = max(left[0], left[1]) + max(right[0], right[1]);
return {val2, val1};
}
int rob(TreeNode
vectorret = traversal(root);
return max(ret[0], ret[1]);}
};