第一題
題解:直接模擬
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;
}
};