题目
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?
m and n will be at most 100.
思路
其实就是一个排列组合的问题,mxn的矩形,其实就是向右走m-1步,向下走n-1步。即求 Cmin(n−1,m−1)m−1+n−1 。
代码
class Solution {
public:
int uniquePaths(int m, int n) {
if (m == 1 || n == 1) {
return 1;
}
if (m * n == 0) {
return 0;
}
int downNum = m - 1 + n - 1;
int upNum = min(n - 1, m - 1);
long result = 1;
for (int i = downNum; i > downNum - upNum; i--) {
result *= i;
}
for (int i = upNum; i > 1; i--) {
result /= i;
}
return result;
}
};