LeetCode 1301. Number of Paths with Max Score
[“E23”,
" 2X2",
“12S”]
given this 2D array, we will start from letter S, and we need to end in the letter E, and we can only move top, left, and top-left, and there might be some obstacles labeled with X,
we need to return two integers:
the first will be the maximum sum we can collect during the path. and the second is the number of path which there sum is the maximum sum, if overflowed, take module 10^9 + 7.
if there is no such path, return the result as [0,0]
也就是说 要找最大加和路径和有多少条这样的路径。
用两个2D dp数组 事实上这道题没有他看起来那么难
class Solution {
private final int[][] DIRS = new int[][]{{0,-1},{-1,0},{-1,-1}};
public int[] pathsWithMaxScore(List<String> board) {
int m = board.size();
int n = board.get(0).length();
//two 2D dp array, one is maintain the sum and another is maintain the path count
int[][] sum = new int[m][n];
int[][] count = new int[m][n];
count[m-1][n-1] = 1;
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
if (count[i][j] == 0) continue;
for (int[] dir: DIRS) {
int ni = i + dir[0];
int nj = j + dir[1];
if (ni >= 0 && nj >= 0 && board.get(ni).charAt(nj) != 'X') { //if not out of boundary and not obstacle
int nsum = sum[i][j];
if (board.get(ni).charAt(nj) != 'E') {
nsum += board.get(ni).charAt(nj) - '0';
}
//check if we need to have an update
if (nsum > sum[ni][nj]) { //if the sum needs to be updated, then
count[ni][nj] = count[i][j];
sum[ni][nj] = nsum;
} else if (nsum == sum[ni][nj]) { //this
count[ni][nj] = (count[ni][nj] + count[i][j]) % 1000000007;
}
}
}
}
}
return new int[]{sum[0][0], count[0][0]};
}
}

浙公网安备 33010602011771号