前言
本帖主要是记录在LeetCode刷题笔记,持续更新中。
会议安排
// 1.会议室安排,输入为每个会议的起止时间,会议有冲突,要求尽可能多的会议。
struct Agent{
Agent(){
name = "invalid";
start = 0;
end = 0;
}
Agent(std::string a, int b, int c){
name = a;
start = b;
end = c;
}
std::string name;
float start;
float end;
bool operator<(const Agent& b) const{
return this->end < b.end;
}
};
std::vector<Agent> BestAgentArrange(std::vector<Agent> agents, float start){
std::sort(agents.begin(), agents.end());// 按照结束时间的早晚排序
std::vector<Agent> res;
for(auto ele : agents){
if(ele.start > start){
res.push_back(ele);
start += ele.end; //上一会议的结束时间作为开始时间
}
}
return res;
}
拼凑字符串
// 2.拼凑字符串使得字典数最小
struct MyCompareDict{
bool operator()(std::string& lhs, std::string& rhs){
return lhs + rhs < rhs + lhs;
}
};
std::string MinDictMerge(std::vector<std::string> ss){
std::string res;
sort(ss.begin(), ss.end(), MyCompareDict());
for(auto ele : ss){
res += ele;
}
return res;
}
Hulfman编码
// 3.Hulfman编码 要求list分割黄金,使得分割成本最低
int HulfmanCode(const std::vector<int>& list){
int res = 0;
int cur = 0;
std::priority_queue<int> temp(list.begin(),list.end());
while(temp.size() > 1){
cur = temp.top();
temp.pop();
cur += temp.top();
temp.pop();
res += cur;
}
return res;
}
总结
局部最优->全局最优,代码都很短。
解题技巧:
1,举例全排列,暴力解法,即写一个对数器,
2,脑补几个贪心算法,用1验证,
3,不要纠结算法推导,证明较难,费时间。
局部最优并保证传递性(数学归纳法),最后对算法的结果后验:假设法。