1. LeetCode 5854. 学生分数的最小差值
排序,模拟
class Solution {
public:
int minimumDifference(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int res = 1e9;
for(int i = 0;i + k - 1 < nums.size();i ++ )
res = min(res, nums[i + k - 1] - nums[i]);
return res;
}
};
2. LeetCode 5855. 找出数组中的第 K 大整数
字符串排序
class Solution {
public:
string kthLargestNumber(vector<string>& nums, int k) {
sort(nums.begin(), nums.end(), [&](string &a, string &b){
if(a.size() != b.size()) return a.size() > b.size();
return a > b;// 这里如果添加=就会报错,如果a排在b前面返回true
});
return nums[k - 1];
}
};
3. LeetCode 5856. 完成任务的最少工作时间段
状态压缩DP
const int N = 16, M = 1 << N;
int f[M][N]; // st[i], j剩余空间
class Solution {
public:
int minSessions(vector<int>& tasks, int m) {
int n = tasks.size();
memset(f, 0x3f, sizeof f);
f[0][0] = 0;
for(int st = 0;st < (1 << n) - 1;st ++ )
for(int t = 0;t < n;t ++ )
{
if(!(st >> t & 1))
{
int next_state = st | (1 << t);
for(int j = 0;j <= m;j ++ )
{
if(j >= tasks[t]) f[next_state][j - tasks[t]] = min(f[next_state][j - tasks[t]], f[st][j]);
else f[next_state][m - tasks[t]] = min(f[next_state][m - tasks[t]], f[st][j] + 1);
}
}
}
int res = INT_MAX;
for(int i = 0;i < m;i ++ ) res = min(res,f[(1 << n) - 1][i]);
return res;
}
};
//作者:彩色铅笔
//链接:https://www.acwing.com/activity/content/code/content/1715698/
//来源:AcWing
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
4. LeetCode 5857. 不同的好子序列数目
倒着分段DP
class Solution {
public:
int numberOfUniqueGoodSubsequences(string s) {
int n = s.size();
int dp0 = 0, dp1 = 0, mod = 1e9 + 7, has0 = 0;
for(int i = n-1; i >= 0; --i) {
if(s[i] == '0') {
has0 = 1;
dp0 = (dp0 + dp1 + 1) % mod;
} else {
dp1 = (dp0 + dp1 + 1) % mod;
}
}
return (dp1 + has0) % mod;
}
};
// 作者:newhar
// 链接:https://leetcode-cn.com/problems/number-of-unique-good-subsequences/solution/dong-tai-gui-hua-jing-dian-ti-mu-de-bian-n4h3/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。