LeetCodeLC88: unique-paths (java implementation)

Title description

A robot is in the upper left corner of an m×n map (starting point, the position marked "start" in the figure below).

The robot moves down or to the right every time. The robot has to reach the lower right corner of the map. (End point, the position marked "Finish" in the figure below).

How many different paths can be taken from the start to the end?

The picture above is a 3×7 size map. How many different paths are there?

Remarks: m and n are less than or equal to 100

Example 1

enter

2,1

Output

1

Example 2

enter

2,2

Output

2

 Idea: Typical simple DP question. It is implemented by recursion, and each element in the two-dimensional array ways[][] is used to represent the number of paths from the point to the end point. Scan the two-dimensional array from bottom right to top left to recursively assign values. The answer is the size of ways[0][0].

1. Determine the boundary: It is not difficult to find that there can be only one path on the bottom row and the rightmost column. So ways[m-1][k](k=0,1,....)=1,ways[k][n-1](k=0,1,....)=1

2. Determine the state transition equation: ways[m][n]=ways[m+1][n]+ways[m][n+1]. (Except for special boundary points) That is, the number of paths from a certain point to the end point = the number of paths from one square to the right of the point + the number of paths from the next square to the end point.

3. Deal with special cases, such as directly return 1 when m=1, n=1.

public class Solution {
    public int uniquePaths (int m, int n) {

        if(m==1&&n==1)
            return 1;
        int [][]ways=new int[m][n];
        int i,j;
        for(j=0;j<n-1;j++)
            ways[m-1][j]=1;
        for(i=0;i<m-1;i++)
            ways[i][n-1]=1;
        for(i=m-1;i>=0;i--)
            for(j=n-1;j>=0;j--){
                if(i==m-1&&j==n-1)
                    continue;
                if(i==m-1||j==n-1){
                    ways[i][j]=1;
                    continue;
                }
                ways[i][j]=ways[i][j+1]+ways[i+1][j];
            }
        return ways[0][0];
    }
}

 

Guess you like

Origin blog.csdn.net/Zhongtongyi/article/details/107242358