738.单调递增的数字
https://leetcode.cn/problems/monotone-increasing-digits/
暴力:
class Solution {
public:
int monotoneIncreasingDigits(int n) {
vector<int> vec;
while(n) {
vec.push_back(n % 10);
n /= 10;
}
for (int i = 1; i < vec.size(); i++) {
if (vec[i] > vec[i - 1]) {
for (int j = i - 1; j >= 0; j--) {
vec[j] = 9;
}
vec[i]--;
}
}
for (int i = vec.size() - 1; i >= 0; i--) {
n *= 10;
n += vec[i];
}
return n;
}
};
贪心:
class Solution {
public:
int monotoneIncreasingDigits(int n) {
string N = to_string(n);
int flag = N.length();
for (int i = N.length() - 1; i > 0; i--) {
if (N[i - 1] > N[i]) {
N[i - 1]--;
flag = i;
}
}
for (int i = N.length() - 1; i >= flag; i--) {
N[i] = '9';
}
return stoi(N);
}
};
968.监控二叉树
https://leetcode.cn/problems/binary-tree-cameras/
class Solution {
public:
int result;
int traversal(TreeNode* cur) {
if (!cur) return 2;
int left = traversal(cur->left);
int right = traversal(cur->right);
if (left == 0 || right == 0) {
result++;
return 1;
}
if (left == 1 || right == 1) {
return 2;
}
return 0;
}
int minCameraCover(TreeNode* root) {
result = 0;
if (traversal(root) == 0) result++;;
return result;
}
};