Unique Path

LeetCode #62


Description:

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?

Example:

Note

Idea:

DP

DP[0][0]==1

DP[i][j] = DP[i-1][j] + DP[i][j-1];

Code:

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int>> DP(m, vector<int>(n, 0));

        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(i==0 && j==0) DP[i][j] = 1;
                else if(i==0) DP[i][j] = DP[i][j-1];
                else if(j==0) DP[i][j] = DP[i-1][j];
                else DP[i][j] = DP[i-1][j] + DP[i][j-1];
            }
        }

        return DP[m-1][n-1];

    }
};

results matching ""

    No results matching ""