https://leetcode.com/problems/unique-paths/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?

Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
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 -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3 Output: 28中文翻譯:
一個m x n的矩陣,左上角(0,0)有一個機器人,右下角(m,n)是終點。
機器人每次只能向右或向下走,請問走到終點有多少走法?
[Solution]
Dynamic Programming.
The answer of (x,y) = answer of (x,y-1) + answer of (x-1,y).
The robot can only move 1 step down or 1 step right.
So, if the robot is on position (x,y), the previous position must be (x,y-1) or (x-1,y).
So the number of ways to get to (x,y), is equal to
the number of ways to get to (x,y-1) + the number of ways to get to (x-1,y).
1.Top down: recursive call from (x,y) --> (0,0)
2.Bottom up: build table from (0,0) --> (x,y)
We choose method 2 because the information will be used repeatedly.
The space complexity is O(m*n)
The time complexity is O(m*n)
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> matrix(m+1, vector<int>(n+1,0));
matrix[1][0]=1;
for(int r=1;r<=m;r++){
for(int c=1;c<=n;c++){
matrix[r][c]=matrix[r][c-1] + matrix[r-1][c];
}
}
return matrix[m][n];
}
};
There is advance solution which saves more memory space.
During building table, we found that we only need the last row.
So we only to declare a table which size is 2 rows, one for current, one for previous.
The space complexity is O(n).
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> matrix(2, vector<int>(n+1,0));
matrix[1][0]=1;
for(int r=1;r<=m;r++){
for(int c=1;c<=n;c++){
matrix[r%2][c]=matrix[r%2][c-1] + matrix[(r-1)%2][c];
}
if(r==1) matrix[1][0]=0;
}
return matrix[m%2][n];
}
};