Wednesday, July 29, 2015

LintCode (114) 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?
Have you met this question in a real interview? 
Yes
Example
1,11,21,31,41,51,61,7
2,1





3,1




3,7

Above is a 3 x 7 grid. How many possible unique paths are there?

Note
m and n will be at most 100.

Dp:
求解得数目,走table, matrix dp
f[i][j] 为 从0,0走到i,j的路径数
转化方程 f[i][j]= f[i-1][j]+f[i][j-1]
解: f[m-1][n-1]


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    /**
     * @param n, m: positive integer (1 <= n ,m <= 100)
     * @return an integer
     */
    int uniquePaths(int m, int n) {
        // wirte your code here
        vector<vector<int>> tbl(m, vector<int>(n,1));
        for(int i=1; i<m; i++){
            for (int j=1; j<n; j++){
                tbl[i][j]=tbl[i-1][j]+tbl[i][j-1];
            }
        }
        return tbl[m-1][n-1];
    }
};

No comments:

Post a Comment