Leetcode (Java) -62. Different Path

A robot located in a left corner mxn grid (starting point figure below labeled "Start").

The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").

Q. How many different paths there are in total?

For example, the map is a grid of 7 x 3. How many possible paths have?

Description: the values ​​of m and n is not more than 100.

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From top left corner, a total of three paths to the lower right corner.
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> right -> right
Example 2:

Input: m = 7, n = 3
Output: 28

Ideas: Dynamic Programming DP

Since the robot can move up and down movement of the right, so the total number of [i, j] shall be equal to the lattice [i - 1, j] + [i, j -1], because the first [i, j] is the lattice constant or move left over from above.

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m][n];
        for(int i=0;i<m;i++)
        {
            dp[i][0]=1;
        }
        for(int i=0;i<n;i++)
        {
            dp[0][i]=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];
    }
}

 

He published 192 original articles · won praise 32 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_38905818/article/details/104226552