π One-stop destination for all your technical interview Preparation π
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?
class Solution {
private:
int uniquePathsHelper(int m, int n, int i, int j)
{
if (i == m - 1 && j == n - 1)
return 1;
if (i >= m || j >= n)
return 0;
int right = uniquePathsHelper(m, n, i, j + 1);
int down = uniquePathsHelper(m, n, i + 1, j);
return right + down;
}
public:
int uniquePaths(int m, int n)
{
return uniquePathsHelper(m, n, 0, 0);
}
};
class Solution {
private:
int dp[101][101];
int uniquePathsHelper(int m, int n, int i, int j)
{
if (i == m - 1 && j == n - 1)
return 1;
if (i >= m || j >= n)
return 0;
if (dp[i][j] != -1)
return dp[i][j];
int right = uniquePathsHelper(m, n, i, j + 1);
int down = uniquePathsHelper(m, n, i + 1, j);
return dp[i][j] = right + down;
}
public:
int uniquePaths(int m, int n)
{
memset(dp, -1, sizeof(dp));
return uniquePathsHelper(m, n, 0, 0);
}
};