738.单调递增的数字
题目链接
我的题解
class Solution {
public:
int monotoneIncreasingDigits(int n) {
string s = to_string(n);
for (int i = s.size() - 2; i >= 0; i --) {
if (s[i] > s[i + 1]) {
s[i] --;
for (int j = i + 1; j < s.size(); j ++) s[j] = '9';
}
}
return stoi(s);
}
};
714. 买卖股票的最佳时机含手续费
题目链接
我的题解
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int res = 0, min_price = prices[0];
for (int i = 0; i < prices.size(); i ++) {
min_price = min(min_price, prices[i]);
if (prices[i] > min_price + fee) {
res += prices[i] - min_price - fee;
min_price = prices[i] - fee;
}
}
return res;
}
};
968.监控二叉树
题目链接
我的题解
/**
* 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 {
//val = 0;未被监视
//val = 1;被监视但没摄像机
//val = 2;有摄像机
int res = 0;
void backTracking(TreeNode* root) {
if (root == nullptr) return;
backTracking(root->left);
backTracking(root->right);
if (root->left == nullptr && root->right == nullptr) return;
if ((root->left && root->left->val == 0) || (root->right && root->right->val == 0)) {
if (root->left) root->left->val = 1;
if (root->right) root->right->val = 1;
root->val = 2;
res ++;
return;
}
if ((root->left && root->left->val == 2) || (root->right && root->right->val == 2)) {
root->val = 1;
}
return;
}
public:
int minCameraCover(TreeNode* root) {
TreeNode * node = new TreeNode;
node->left = root;
backTracking(node);
return res;
}
};