【LeetCode】62. Unique Paths 不同路径(Medium)(JAVA)每日一题

【LeetCode】62. Unique Paths 不同路径(Medium)(JAVA)

题目地址: 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?

Example 1:


Input: m = 3, n = 7
Output: 28

Example 2:

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

Example 3:

Input: m = 7, n = 3
Output: 28

Example 4:

Input: m = 3, n = 3
Output: 6

Constraints:

  • 1 <= m, n <= 100
  • It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

题目大意

一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。

机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。

问总共有多少条不同的路径?

解题方法

这题其实用的是数学上的技巧。

  1. m x n 的网格,往右需要走 m - 1 步,往下需要走 n - 1 步,总共走 m + n - 2 步
  2. 只要找出往右走的 n - 1 步在 m + n - 2 步中有多少种情况即可: C m + n − 2 n − 1 C^{n - 1}_{m + n - 2} Cm+n2n1
class Solution {
    public int uniquePaths(int m, int n) {
        int min = m > n ? n : m;
        long res = 1;
        for (int i = 1; i <= min - 1; i++) {
            res = res * (m + n - 1 - i) / i;
        }
        return (int) res;
    }
}

执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:35.2 MB,击败了79.10% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值