Press "Enter" to skip to content

花花酱 LeetCode 1301. Number of Paths with Max Score

You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.

You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.

Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.

In case there is no path, return [0, 0].

Example 1:

Input: board = ["E23","2X2","12S"]
Output: [7,1]

Example 2:

Input: board = ["E12","1X1","21S"]
Output: [4,2]

Example 3:

Input: board = ["E11","XXX","11S"]
Output: [0,0]

Constraints:

  • 2 <= board.length == board[i].length <= 100

Solution: DP

dp[i][j] := max score when reach (j, i)
count[i][j] := path to reach (j, i) with max score

m = max(dp[i + 1][j], dp[i][j+1], dp[i+1][j+1])
dp[i][j] = board[i][j] + m
count[i][j] += count[i+1][j] if dp[i+1][j] == m
count[i][j] += count[i][j+1] if dp[i][j+1] == m
count[i][j] += count[i+1][j+1] if dp[i+1][j+1] == m

Time complexity: O(n^2)
Space complexity: O(n^2)

C++

请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website
您可以通过在亚马逊上购物(任意商品)来支持我们

Paypal
Venmo
huahualeetcode
微信打赏

Be First to Comment

Leave a Reply