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 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
- Total Accepted: 125270
- Total Submissions: 315617
- Difficulty: Medium
- Contributors: Admin
题目大意是限定机器人每次只能往右或者往下走,求存在多少个不同的路径,能让机器人从左上角走到右下角。
由于机器人只能往右或者往下走,所以整个路径的长度是左上角跟右下角的街区距离,即m+n-2。而且路径中必然有m-1次往右走以及n-1次往下走。
给路径中每一步编号为1,2,3...m+n-2,不同路径之间的差别是选择哪几部往下走,因此共有C(m+n-2,n-1)种路径。
考虑到直接用公式计算C(m+n-2,n-1)的话,会出现(m+n-2)!这样比较大的中间结果。
为了避免溢出,使用公式C(n,m+1)=C(n,m)*(n-m)/(m+1)进行迭代计算。
代码如下:
class Solution {
public:
int uniquePaths(int m, int n) {
if(n>m)
swap(m,n);
if(n==1)
return 1;
m--;
n--;
long res=m+n;
for(int i=1;i<n;i++)
res=res*(m+n-i)/(i+1);
return res;
}
};
Submission Details
61 / 61 test cases passed.
| Status: Accepted |
Runtime:
3 ms
|
Submitted:
0 minutes ago
|