Problem: A robot is located at the top-left corner(0, 0) 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 (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Example:
Input: m = 3, n = 7 Output: 28
Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down
Approach: It's a simple DP problem. Just look at the implemetation to understand the approach.
Implementation in C#:
public int UniquePaths(int m, int n)
{
int[,] table = new int[m, n];
for (int i = 0; i < m; ++i)
{
table[i, 0] = 1;
}
for (int i = 0; i < n; ++i)
{
table[0, i] = 1;
}
for (int i = 1; i < m; ++i)
{
for (int j = 1; j < n; ++j)
{
table[i, j] = table[i - 1, j] + table[i, j - 1];
}
}
return table[m - 1, n - 1];
}
Complexity: O(m * n)
No comments:
Post a Comment