leetcode

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?

   |1|2|3|       |1|1|1|

   |4|5|6|   ->  |1|2|3| 

   |7|8|9|       |1|3|6|

这道是最简单的DP问题之一,通过观察可以发现 f(5) = f(2) + f(4), 也就是说f(i,j) = f(i-1, j) + f(i, j-1);

public int uniquePaths(int m, int n) {
        int[][] results = new int[m][n];

        //initialize all values
        for (int i=0; i<m; i++) {
            for (int j=0; j<n; j++) {
                results[i][j] = 1;
            }
        }

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

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