337,打家劫舍III 难点: 1.通过递归后续遍历来实现递推公式 2.如何设计vector数组用来存储结果
class Solution {
private:
vector<int> robtree(TreeNode* root){
if(root==nullptr) return vector<int>{0,0};
vector<int> left=robtree(root->left);
vector<int> right=robtree(root->right);
//盗窃root
int val1=root->val+left[0]+right[0];
//不盗窃root
int val2=max(left[0],left[1])+max(right[0],right[1]);
return {val2,val1};
}
public:
int rob(TreeNode* root) {
vector<int> result=robtree(root);
return max(result[0],result[1]);
}
};
121.买卖股票的最佳时机 1.采用贪心算法 通过设计两个变量,一个记录结果,一个记录最小股票值
class Solution {
public:
int maxProfit(vector<int>& prices) {
int low=INT_MAX;
int result=0;
for(int i=0;i<prices.size();i++){
low=min(low,prices[i]);//选出最小的一只股票
result=max(result,prices[i]-low);//更新result,因为i是从左至右迭代的,所以可以保证是买入卖出顺序
}
return result;
}
2.动态规划算法
class Solution {
public:
int maxProfit(vector<int>& prices) {
//采用动态规划、
int len=prices.size();
if(len==0) return 0;
vector<vector<int>> dp(len,vector<int>(2));//dp[i][0]表示持有股票,dp[i][1]表示不持有股票
//初始化
dp[0][0]=-prices[0];
dp[0][1]=0;
for(int i=1;i<len;i++){
dp[i][0]=max(dp[i-1][0],-prices[i]);
dp[i][1]=max(dp[i-1][1],dp[i-1][0]+prices[i]);
}
return dp[len-1][1];
}
};
123.买卖股票问题
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() == 0) return 0;
vector<int> dp(5, 0);
dp[1] = -prices[0];
dp[3] = -prices[0];
for (int i = 1; i < prices.size(); i++) {
dp[1] = max(dp[1], dp[0] - prices[i]);
dp[2] = max(dp[2], dp[1] + prices[i]);
dp[3] = max(dp[3], dp[2] - prices[i]);
dp[4] = max(dp[4], dp[3] + prices[i]);
}
return dp[4];
}
};