[LeetCode] 62. Unique Paths

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 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.

Thought process:
  1. Sub-problem: how many unique paths are there from top-left corner to any point.
  2. Formula: f[i][j] = f[i - 1][j] + f[i][j - 1].
  3. Initialization: there is only one path from top-left corner to a point on the first row or column.
  4. Answer: f[m - 1][n - 1].

Solution 1 (DP):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public int uniquePaths(int m, int n) {
        if (m == 0 || n == 0) {
            return 0;
        }
        
        int[][] f = new int[m][n];
        Arrays.fill(f[0], 1);
        for (int i = 0; i < m; i++) {
            f[i][0] = 1;
        }
        
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                f[i][j] = f[i - 1][j] + f[i][j - 1];
            }
        }
        return f[m - 1][n - 1];
    }
}

Time complexity: O(mn).

Solution 2 (Combination):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public int uniquePaths(int m, int n) {
        int N = m + n - 2;
        double result = 1;
        
        for (int i = 1; i < m; i++) {
            result = result * (N - (m - 1) + i) / i;
        }
        return (int) result;
    }
}

Time complexity: O(m + n).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula