LeetCode 62. Unique Paths

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?


This is a classical DP problem. The most important part is to initialize the status correctly.

  int uniquePaths(int m, int n) {
    vector< vector<int> > map(m, vector<int>(n, 0));

    // initialize the matrix
    for(int i = 0; i < m; ++i) {
        map[i][0] = 1;  // there is one one way to go right straightly.
    }

    for(int j = 0; j < n; ++j) {
        map[0][j] = 1;  // there is one way to go down straightly
    }

    for(int i = 1; i < m; ++i) {
        for(int j = 1; j < n; ++j) {
            map[i][j] = map[i-1][j] + map[i][j-1];  // the most recent cube path is from right top and left down.
        }
    }
    return map[m-1][n-1];  // the right down conner one is the sum of the whole path.
 }





你可能感兴趣的:(LeetCode 62. Unique Paths)