【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”)。
问总共有多少条不同的路径?
解题方法
这题其实用的是数学上的技巧。
- m x n 的网格,往右需要走 m - 1 步,往下需要走 n - 1 步,总共走 m + n - 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,击败了100.00% 的Java用户
内存消耗:35.2 MB,击败了79.10% 的Java用户