114.Unique Paths

1.Description(Easy)

A robot is located at the top-left corner of a mxn grid.

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.

How many possible unique paths are there?

Notice

m and n will be at most 100.

Example

Given m =3and n =3, return6. Given m =4and n =5, return35.

2.Code

坐标型动态规划(统计方案个数)

public int uniquePaths(int m, int n) {
        if(m<=0 || n<=0){
            return -1;
        }
         //state:the number of path from(0,0) to (x,y)
        int[][] num=new int[n][m];

        //initialization:
        num[0][0]=1;
        for(int i=1;i<m;i++){
            num[0][i]=1;
        }
        for(int i=1;i<n;i++){
            num[i][0]=1;
        }

        //function:
        for(int i=1;i<n;i++){
            for(int j=1;j<m;j++){
                num[i][j]=num[i-1][j]+num[i][j-1];
            }
        }

        return num[n-1][m-1];
    }

Last updated