暴力搜索(超时)
跳不过去时,每次我们可以选择用砖块,也可以选择用梯子,所以我们有如下做法
class Solution {
public:
int furthestBuilding(vector<int>& heights, int bricks, int ladders) {
dfs(heights,0,bricks,ladders);
return res;
}
int res = 0;
void dfs(vector<int>& heights, int i, int bricks, int ladders){
if(res==heights.size()-1){
return;
}
if(i==heights.size()-1){
res = i;
return;
}
if(bricks - heights[i+1] + heights[i]<0&&ladders==0){
res = max(res,i);
return;
}
if(heights[i]>=heights[i+1]){
dfs(heights,i+1,bricks,ladders);
}else{
if(bricks - heights[i+1] + heights[i]>=0){
dfs(heights,i+1,bricks - heights[i+1] + heights[i],ladders);
}
if(ladders>0){
dfs(heights,i+1,bricks,ladders-1);
}
}
}
};
思考将递归改成记忆话搜索(空间复杂度极大)
贪心加延迟决策
我们知道梯子一定要用在高度差最大的时候,那么我们如何知道此时高度差最大,我们就要用梯子。答案是我们延迟决策,遇到跳不过去的时候,我们假设能用梯子就用梯子。当梯子用完的时候,我们回头去看前面高度差最小的地方,把它换成砖块。直到砖块不能替换时。此时我们找到了最远的距离。
class Solution {
public:
int furthestBuilding(vector<int>& heights, int bricks, int ladders) {
priority_queue<int, vector<int>, greater<int>> q;
int count = 0;
for(int i=0;i<heights.size()-1;i++){
if(heights[i]>=heights[i+1]){
continue;
}
q.push(heights[i+1]-heights[i]);
count++;
if(count>ladders){
int diff = q.top();
q.pop();
if(bricks>=diff){
bricks-=diff;
count--;
}else{
return i;
}
}
}
return heights.size() - 1;
}
};