62. Unique Paths

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?

Analysis

link: https://www.youtube.com/watch?v=GO5QHC_BmvM

T[i][j] = T[i - 1][j] + T[i][j - 1] 因为看的是unique path, 所以不用加1

Solution

public int uniquePaths(int m, int n) {
    int[][] matrix = new int[m][n];
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i == 0) {
                matrix[i][j] = 1;
                continue;
            }
            if (j == 0) {
                matrix[i][j] = 1;
                continue;
            }
            int up = matrix[i - 1][j];
            int left = matrix[i][j - 1];
            matrix[i][j] = up + left;
        }
    }
    return matrix[m - 1][n - 1];
}

results matching ""

    No results matching ""