如何为LeetCode最小加油次数问题设计递归解决方案?已实现递归代码但无法通过全部测试用例求助
Fixing Recursive Solution for "Minimum Number of Refueling Stops"
Let's break down the issues in your current code and fix them step by step—since you specified you only care about the recursive approach, I'll keep that front and center.
Key Issues in Your Code
- Incorrect Memoization Key: Your memo only uses
targetandcurrentFuel, but it's missing thestartindex. The state of our recursion depends on which stations we've already passed, so omittingstartleads to caching wrong results for different scenarios. - Confusing Distance Calculation: The
initialDistancelogic overcomplicates tracking fuel consumption to reach a station, leading to miscalculations of remaining fuel and target distance. - Unnecessary Target Adjustment: The way you modify
targetin recursive calls adds confusion; we can simplify how we track remaining distance to the end.
Corrected Recursive Code
import java.util.HashMap; import java.util.Map; class Solution { private static int totalTarget; private static int helper(int remainingDistance, int currentFuel, int startIdx, int[][] stations, Map<String, Integer> memo) { // If current fuel is enough to reach the end, no stops needed if (currentFuel >= remainingDistance) { return 0; } // No stations left to check, can't reach the end if (startIdx == stations.length) { return -1; } // Unique key for memo: includes all state variables String memoKey = remainingDistance + "," + currentFuel + "," + startIdx; if (memo.containsKey(memoKey)) { return memo.get(memoKey); } int minStops = Integer.MAX_VALUE; // Farthest we can go right now without refueling int maxReachable = (totalTarget - remainingDistance) + currentFuel; for (int i = startIdx; i < stations.length; i++) { int stationPos = stations[i][0]; // Stations are sorted—if this one is out of reach, the rest are too if (stationPos > maxReachable) { break; } // Fuel needed to drive from current position to this station int fuelToStation = stationPos - (totalTarget - remainingDistance); // Fuel left after arriving at the station int fuelAfterArrival = currentFuel - fuelToStation; // Remaining distance from this station to the end int newRemaining = totalTarget - stationPos; // Recurse: we choose to refuel here, so add 1 to stop count int recursiveResult = helper(newRemaining, fuelAfterArrival + stations[i][1], i + 1, stations, memo); if (recursiveResult != -1) { minStops = Math.min(minStops, 1 + recursiveResult); } } // If no valid refuel path found, return -1; else return the minimum stops int finalResult = (minStops == Integer.MAX_VALUE) ? -1 : minStops; memo.put(memoKey, finalResult); return finalResult; } public static int minRefuelStopsBruteForce(int target, int startFuel, int[][] stations) { totalTarget = target; // Quick edge case: no stops needed at all if (startFuel >= target) { return 0; } return helper(target, startFuel, 0, stations, new HashMap<>()); } }
What Changed?
- Memoization Fix: Added
startIdxto the memo key to ensure we cache results for the exact state (remaining distance, current fuel, and which stations are still available to choose from). - Simplified Distance Tracking: We track
remainingDistanceas the direct distance left to the end. Our current position is calculated astotalTarget - remainingDistance, making it easy to compute fuel needed to reach any station. - Early Loop Exit: Since stations are sorted by position, once we hit a station we can't reach, we break the loop early to save unnecessary computations.
- Clearer Recursive Flow: When refueling at a station, we pass the new remaining distance (from the station to the end) and updated fuel (after driving to the station plus refueling).
Testing Tips
Make sure to test edge cases like:
- No stations available (check if start fuel covers the target)
- All stations are unnecessary (start fuel is enough to reach the end)
- Needing to refuel at every station to reach the end
- A station that sits exactly at the maximum reachable distance with current fuel
内容的提问来源于stack exchange,提问作者IkhideIfidon
相关产品推荐
相关产品推荐

