[leetcode] 871. Minimum Number of Refueling Stops

A car travels from a starting position to a destination which is target miles east of the starting position.

Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.

The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.

When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.

Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

class Solution {
public:
    //方法1:动态规划
    int minRefuelStops(int target, int startFuel, vector>& stations) {
        int num_station = stations.size();
        
        vector dp(num_station+1,startFuel);// i个加油站最远可以去多远
        
        // 油量小于目的地
        for(int i = 0; i< num_station && stations[i][0] < target; i++){//加油站的个数
            for(int j = i + 1; j>= 1; j--)//使用的加油站的个数
            {
                if(dp[j-1] >= stations[i][0]) // 保证可以从前一个加油站到目前的加油站
                    dp[j] = max(dp[j], dp[j-1]+ stations[i][1]);
            }
        }
        for(int i =0;i<=num_station;i++)
        {
            if(dp[i]>=target){
                return i;
            }
        }
        return -1;
    }
    
    //方法2:优先队列
    int minRefuelStops(int target, int startFuel, vector>& stations) {
        int  cur = startFuel;
        int steps = 0;
        int i = 0;
        
        priority_queue q;
        
        while(true){
            // 到达终点了
            if(cur >= target) return steps;
            // 把沿途的加油站记录下来 ,找到油量不能支持的前一个加油站
            while(i < stations.size() &&  cur >= stations[i][0])
                q.push(stations[i++][1]);
            // 无法到达终点
            if(q.empty())
                break;
            //在没油的时候,选择沿途油量最多的一个加油站加油
            cur += q.top();
            q.pop();
            steps++;
        }
        return -1;
    }
};

参考资料
题目地址

你可能感兴趣的:([leetcode] 871. Minimum Number of Refueling Stops)