【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?
Above is a 7 x 3 grid. How many possible unique paths are there?
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
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+n−2n−1
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, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 36.2 MB, 在所有 Java 提交中击败了 5.01% 的用户