第一题
题解:直接模拟
class Solution {
public:
vector<string> divideString(string s, int k, char fill) {
vector<string> res;
int n = s.size();
string t ="";
for(int i=0; i<n; i++){
t += s[i];
if(t.size() == k){
res.push_back(t);
t = "";
}
}
if(t.size() > 0){
int len = k - t.size();
for(int i=0; i<len; i++) t+= fill;
res.push_back(t);
}
return res;
}
};
第二题
题解: 模拟,逆向思维,倒着求解
class Solution {
public:
int minMoves(int target, int maxDoubles) {
int res = 0;
while(target > 1){
if(maxDoubles == 0){
return res + target-1;
}
if(target%2 == 0){
target /= 2;
maxDoubles--;
res++;
}else{
target--;
res++;
}
}
return res;
}
};
第三题
比赛想到的是dfs,写完提交 TLE, 比赛快结束了,想到DP,比赛期间没有写出来,看其他人的提交,发现记忆化dfs可以过。
class Solution {
public:
long long mostPoints(vector<vector<int>>& questions) {
int n = questions.size();
vector<long long> dp(n+1);
for(int i=0; i<n; i++){
dp[i+1] = max(dp[i], dp[i+1]);
int next = min(n, i+questions[i][1]+1);
dp[next] = max(dp[next], dp[i]+questions[i][0]);
}
return dp[n];
}
};
第四题
class Solution {
public:
bool check(int n, long long t, vector<int>& batteries){
long long sum = 0;
for(auto c : batteries){
sum += min(t, (long long)c);
}
return (sum/t) >= n;
}
long long maxRunTime(int n, vector<int>& batteries) {
long long l = 1, r = 1e15;
while(l < r){
long long mid = l+r+1 >>1;
if(check(n, mid, batteries)){
l = mid;
}else{
r = mid-1;
}
}
return l;
}
};