用了两种方法。
第一种是直接计算组合数,C(m-1, m+n-2),本来以为会溢出,m, n最大能到100,结果测试数据还是过了。
第二种是dp,dp[i][j] = dp[i-1][j]+dp[i][j-1,dp[i][j]表示到达坐标为(i,j)方格的方案数。
Solution 1:
class Solution {
public:
int uniquePaths(int m, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int s = m+n-2, r = min(m-1, n-1);
long long ans = 1;
for(int i = 0, j = 1; i < r; i++){
ans *= (s-i);
for(; j <= r && ans % j == 0; j++)
ans /= j;
}
return ans;
}
};
Solution 2:
class Solution {
public:
int uniquePaths(int m, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > dp(m, vector<int>(n, 1));
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
dp[i][j] = dp[i-1][j]+dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};