Thursday, April 20, 2017

[LintCode] 114 Unique Paths 解题报告

Description
A robot is located at the top-left corner of a m x n 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 = 3 and n = 3, return 6.
Given m = 4 and n = 5, return 35.



思路
这是一道DP的题。
在任何一点,我们知道只可能是从这一点的上面,或者左边走过来。
所以如果我们知道某个点左边点的路径数和上面点的路径数,我们就可以计算到达这个点的路径数。
初始化:从起点一直往下,或者一直往右,都只有一种走法。



Code
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 
        int[][] f = new int[m][n];
        
        for (int i = 0; i < m; i++) {
            f[i][0] = 1;
        }
        
        for (int j = 0; j < n; j++) {
            f[0][j] = 1;
        }
        
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                f[i][j] = f[i - 1][j] + f[i][j - 1];
            }
        }
        
        return f[m - 1][n - 1];
    }
}