1446. 连续字符
代码
class Solution {
public:
int maxPower(string s) {
int tmp = 1, ans = 1;
for (int i = 1; i < s.size(); ++i) {
if (s[i] == s[i - 1]) ans = max(ans, ++tmp);
else tmp = 1;
}
return ans;
}
};
1447. 最简分数
代码
class Solution {
public:
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
vector<string> simplifiedFractions(int n) {
vector<string> ans;
for (int i = 2; i <= n; ++i) {
for (int j = 1; j < i; ++j) {
if (gcd(i, j) == 1) {
ans.push_back(to_string(j) + "/" + to_string(i));
}
}
}
return ans;
}
};
1448. 统计二叉树中好节点的数目
代码
/**
* 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:
int ans = 0;
void dfs(TreeNode* node, int cmax) {
if (!node) return;
if (node->val >= cmax) {
cmax = node->val;
ans++;
}
dfs(node->left, cmax);
dfs(node->right, cmax);
}
int goodNodes(TreeNode* root) {
dfs(root, -1e9);
return ans;
}
};
1449. 数位成本和为目标值的最大数字
思路
完全背包问题求解
f[i, j] = max{f(i - 1, j), f(i, j - cost[j]) + 1};
代码
class Solution {
public:
string largestNumber(vector<int>& cost, int target) {
string ans;
vector<vector<int>> f(10, vector<int>(target + 1));
for (int i = 1; i <= target; ++i) f[0][i] = -1e8;
for (int i = 1; i <= 9; ++i) {
for (int j = 0; j <= target; ++j) {
f[i][j] = f[i - 1][j];
if (j >= cost[i - 1]) f[i][j] = max(f[i][j], f[i][j - cost[i - 1]] + 1);
}
}
if (f[9][target] < 1) return "0";
for (int i = 9, j = target; i ; i--) {
while (j >= cost[i - 1] && f[i][j] == f[i][j - cost[i - 1]] + 1) {
ans += to_string(i);
j -= cost[i - 1];
}
}
return ans;
}
};