从左上到右下路径数
在m*n
的矩阵中,从左上到右下的路径数,只能通过向下和向右走
递归法
public class PathInMatrix {
// 使用递归算法
public int path(int rows, int columns) {
if (rows == 0 && columns == 0) {
return 0;
}
if (rows == 0 || columns == 0) {
return 1;
}
return path(rows -1, columns) + path(rows, columns - 1);
}
}
排列组合
public class PathInMatrix {
// 使用排列组合公式
public double path2(int rows, int columns) {
if (rows == 0 && columns == 0) {
return 0.0;
}
if (rows == 0 || columns == 0) {
return 1.0;
}
// return factorial(rows + columns - 2) /
// (factorial(rows - 1) * factorial(columns - 1));
return factorial(rows + columns)
/ (factorial(rows) * factorial(columns));
}
private double factorial(int n) {
if (n == 0) {
return 1.0;
}
double result = 1.0;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
网友评论