【DP】dp[i]用来记录当前第 i 块区域被覆盖需要多少个最少需要多少个水龙头,每个水龙头的覆盖范围为max(0, i - ranges[i]) 到 min(n, i - ranges[i]),需要注意这里的i是循环的ranges的下标,但是对应的区域其实是 i 左边那一块,所以初始时0这个区域是被覆盖了的,就是坐标轴0点左边[-1, 0]的这个区域,所以初始dp[0] = 0
class Solution {
public int minTaps(int n, int[] ranges) {
int inf = (int)1e5;
int[] dp = new int[n + 1];
for (int i = 0; i <= n; i++) dp[i] = inf;
dp[0] = 0;
for (int i = 0; i <= n; i++) {
int st = Math.max(0, i - ranges[i]), ed = Math.min(n, i + ranges[i]);
int mn = inf;
for (int j = st; j <= ed; j++) mn = Math.min(mn, dp[j]);
for (int j = st; j <= ed; j++) dp[j] = Math.min(dp[j], mn + 1);
}
return dp[n] >= inf? -1: dp[n];
}
}