You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.
At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.
Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).
Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 10^9 + 7.
classSolution { int dp[101][201]; int mod = 1e9 + 7; intsolution(vector<int>& lo, int cur, int dst, int fuel){ if(dp[cur][fuel] != -1) return dp[cur][fuel]; int& res = dp[cur][fuel] = cur == dst;
for(int i = cur + 1; i < lo.size() andabs(lo[i] - lo[cur]) <= fuel; i++) { res = (res + solution(lo, i, dst, fuel - lo[i] + lo[cur])) % mod; }
for(int i = cur - 1; i >= 0andabs(lo[i] - lo[cur]) <= fuel; i--) { res = (res + solution(lo, i, dst, fuel - lo[cur] + lo[i])) % mod; }
return res; } public: intcountRoutes(vector<int>& locations, int start, int finish, int fuel){ memset(dp,-1,sizeof(dp)); int st = locations[start], fin = locations[finish]; sort(locations.begin(), locations.end()); start = lower_bound(locations.begin(), locations.end(), st) - locations.begin(); finish = lower_bound(locations.begin(), locations.end(), fin) - locations.begin(); returnsolution(locations, start, finish, fuel); }