#1575

Count All Possible Routes

Hard
ArrayDynamic ProgrammingMemoizationDynamic ProgrammingMemoizationRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n^2 * fuel)
O(n * fuel)
Space
O(n * fuel)
O(n * fuel)
💡

Intuition

Time O(n * fuel)Space O(n * fuel)

The optimal solution uses dynamic programming with memoization to store results of subproblems, avoiding redundant calculations. This significantly reduces the time complexity by reusing previously computed results.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a memoization table to store results for each city and remaining fuel.
  2. 2Step 2: Define a recursive function that checks all possible routes from the current city to the finish city, using the remaining fuel.
  3. 3Step 3: For each city, calculate the fuel cost to move to other cities and recursively call the function, storing results in the memoization table.
solution.py20 lines
1# Full working Python code
2class Solution:
3    def countRoutes(self, locations, start, finish, fuel):
4        mod = 10**9 + 7
5        n = len(locations)
6        memo = {}  # Memoization dictionary
7
8        def dfs(city, remaining_fuel):
9            if (city, remaining_fuel) in memo:
10                return memo[(city, remaining_fuel)]
11            count = 1 if city == finish else 0
12            for next_city in range(n):
13                if next_city != city:
14                    cost = abs(locations[city] - locations[next_city])
15                    if remaining_fuel >= cost:
16                        count += dfs(next_city, remaining_fuel - cost)
17            memo[(city, remaining_fuel)] = count % mod
18            return memo[(city, remaining_fuel)]
19
20        return dfs(start, fuel)

Complexity note: The time complexity is O(n * fuel) because we explore each city and the remaining fuel can be up to 'fuel'. The space complexity is O(n * fuel) due to the memoization table.

  • 1Using memoization can drastically reduce the number of calculations needed by storing results of subproblems.
  • 2Recursive exploration of routes can be efficiently managed with a well-defined state (city and remaining fuel).

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.