题意:
给你一个 互不相同 的整数数组,其中 locations[i] 表示第 i 个城市的位置。同时给你 start,finish 和 fuel 分别表示出发城市、目的地城市和你初始拥有的汽油总量
每一步中,如果你在城市 i ,你可以选择任意一个城市 j ,满足 j != i 且 0 <= j < locations.length ,并移动到城市 j 。从城市 i 移动到 j 消耗的汽油量为 |locations[i] - locations[j]|,|x| 表示 x 的绝对值。
请注意, fuel 任何时刻都 不能 为负,且你 可以 经过任意城市超过一次(包括 start 和 finish )。
请你返回从 start 到 finish 所有可能路径的数目。
由于答案可能很大, 请将它对 10^9 + 7 取余后返回。
示例 1:
输入:locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5 输出:4 解释:以下为所有可能路径,每一条都用了 5 单位的汽油: 1 -> 3 1 -> 2 -> 3 1 -> 4 -> 3 1 -> 4 -> 2 -> 3
解题思路:
动态规划,定义二维数组dp[i][f] 表示 在城市 i 剩余 燃料为 f 时的方案数
class Solution {
/**
* @param Integer[] $locations
* @param Integer $start
* @param Integer $finish
* @param Integer $fuel
* @return Integer
*/
function countRoutes($locations, $start, $finish, $fuel) {
$dp = array();
$n = count($locations);
for($i = 0; $i < $n; $i++) {
for($j = 0; $j <= $fuel; $j++) {
$dp[$i][$j] = 0;
}
}
$dp[$start][$fuel] = 1;
for($f = $fuel; $f >= 0; $f--) {
for($i = 0; $i < $n; $i++) {
for($j = 0; $j < $n; $j++) {
if($i == $j) {
continue; // 原地不动,所以不计算
}
$dist = abs($locations[$i] - $locations[$j]);
if($f - $dist < 0) {
continue; // 燃油不能支持到达下个地方
}
$dp[$j][$f-$dist] = ($dp[$j][$f-$dist] + $dp[$i][$f]) % (1e9+7); // 从当前位置到i位置的方案数
}
}
}
$ans = 0;
for($f = 0; $f <= $fuel; $f++) {
$ans = ($ans + $dp[$finish][$f]) % (1e9+7);
}
return $ans;
}
}
406



被折叠的 条评论
为什么被折叠?



