内容中心

2026年排名靠前的招工找工作本地招聘排行榜-浙江环讯人力资源有限公司

To solve the problem of finding the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid (moving only right or down), we can use a combinatorial approach for efficiency.

Approach

The key insight here is that to reach the bottom-right corner from the top-left corner, we need to make exactly (m-1) downward moves and (n-1) rightward moves, totaling (m+n-2) moves. The number of unique paths is the number of ways to choose (m-1) downward moves (or equivalently (n-1) rightward moves) from these total moves. This is given by the binomial coefficient C(m+n-2, min(m-1, n-1)), which is calculated as:

[ \text{Paths} = \frac{(m+n-2)!}{(m-1)! \times (n-1)!} ]

To compute this efficiently (without floating-point errors), we calculate the product step-by-step, multiplying the numerator terms and dividing by the denominator terms incrementally.

Solution Code

def uniquePaths(m: int, n: int) -> int:
    if m == 1 or n == 1:
        return 1
    a = m + n - 2
    b = min(m - 1, n - 1)
    result = 1
    for i in range(1, b + 1):
        result = result * (a - b + i) // i
    return result

# Example usage:
# print(uniquePaths(3, 7))  # Output: 28
# print(uniquePaths(2, 2))  # Output: 2

Explanation

  1. Base Case: If either the grid is 1 row or 1 column, there is only one path (all right or all down moves).
  2. Binomial Coefficient: We compute the binomial coefficient C(a, b) where a = m+n-2 (total moves) and b = min(m-1, n-1) (to minimize the number of calculations).
  3. Incremental Calculation: For each step from 1 to b, we multiply the result by the next term in the numerator and divide by the current denominator term, ensuring integer arithmetic to avoid precision issues.

This approach runs in O(min(m, n)) time and O(1) space, making it efficient even for large grid sizes.

Note: This solution assumes the problem is the classic "unique paths in a grid" problem. If the actual problem differs, the approach may need adjustment, but this is a common and widely applicable solution. If you provide more details about the problem, I can refine the solution further.

浙江环讯人力资源有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?