# https://leetcode.com/problems/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 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

"""
from functools import lru_cache
from math import comb, factorial


@lru_cache()
def unique_paths(m: int, n: int) -> int:
    if m <= 0 or n <= 0:
        return 0
    if (m, n) in [(1, 1), (2, 1), (1, 2)]:
        return 1
    else:
        return unique_paths(m, n - 1) + unique_paths(m - 1, n)


def unique_paths(m: int, n: int) -> int:
    mem = {(1, 1): 1}
    for i in range(2, m + 1):
        mem[(i, 1)] = 1
    for j in range(2, n + 1):
        mem[(1, j)] = 1
    for i in range(2, m + 1):
        for j in range(2, n + 1):
            mem[(i, j)] = mem[(i - 1, j)] + mem[(i, j - 1)]
    return mem[(m, n)]


# combinations
def unique_paths(m: int, n: int) -> int:
    return factorial(m + n - 2) // (factorial(m - 1) * factorial(n - 1))


def unique_paths(m: int, n: int) -> int:
    total = m + n - 2
    return comb(total, m - 1)


def unique_paths(m: int, n: int) -> int:
    dp = [[0] * n for _ in range(m)]
    for c in range(n):
        dp[0][c] = 1
    for r in range(m):
        dp[r][0] = 1

    for r in range(1, m):
        for c in range(1, n):
            dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
    return dp[-1][-1]
