Unique Paths 114

Question

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?

Notice

m and n will be at most 100.

Solution

这题和minimum path sum一样要求从左上走到右下,只是这次要求的是一共有多少条路径。和climbling stairs的思想一样。

uniquePath[i][j]表示从(0,0)到(i,j)的路径数之和。

初始化:

uniquePath[0][0] = 1, 
uniquePath[i][0]=uniquePath[i-1][0], 
uniquePath[0][j]=uniquePath[0][j-1]

状态函数:

uniquePath[i][j]=uniquePath[i-1][j]+uniquePath[i][j-1]

即从(0,0)到达(i,j)的路径数为从(0,0)到达其左边和上面的点的路径数之和。

代码如下:

public class Solution {
    /**
     * @param n, m: positive integer (1 <= n ,m <= 100)
     * @return an integer
     */
    public int uniquePaths(int m, int n) {
        // write your code here 
        if(m <= 0 || n <= 0){
            return 0;
        }

        int[][] uniquePath = new int[m][n];
        uniquePath[0][0] = 1;

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

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

        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                uniquePath[i][j] = uniquePath[i][j - 1] + uniquePath[i - 1][j];
            }
        }

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

results matching ""

    No results matching ""