TypechoJoeTheme

IT技术分享

统计

[LeetCode 62] Unique Paths [Java]

2018-02-06
/
0 评论
/
774 阅读
/
正在检测是否收录...
02/06

1. Description

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

2. Example

Given m = 3, n = 7
Return 28

3. Explanation

[tabby title="DP"]

Let dp[i][j] stands for the minimum sum of all numbers along its path when arrive grid (i,j)

(1). init first column
$$for(i : 0 \rightarrow M)$$
$$dp[i][0] = 1$$
(2). init first row
$$for(j : 0 \rightarrow N)$$
$$dp[0][j] = 1$$
(3). $$for(i : 1 \rightarrow M; j : 1 \rightarrow N)$$
$$dp[i][j] = dp[i-1][j] + dp[i][j-1] $$

[tabbyending]

4. Code

public int uniquePaths(int m, int n) {
        if (m < 1 || n < 1) {
            return 0;
        }
        int[][] dp = new int[m][n];

        dp[0][0] = 1;

        for (int i = 1; i < m; i++) {
            dp[i][0] = dp[i - 1][0];
        }

        for (int j = 1; j < n; j++) {
            dp[0][j] = dp[0][j - 1];
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[m - 1][n - 1];
    }
DP
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1125/(转载时请注明本文出处及文章链接)