思路:
动规五部曲:
dp[]含义:每个元素代表到达此处的路径的条数;
递推公式:dp[i][j] = dp[i-1][j] + dp[i][j-1];
dp数组初始化:dp[0][0~(n-1)] = 1,dp[0~(m-1)][0] = 1;
dp数组遍历顺序:从上到下,从左到有依次计算即可;
打印dp数组:将dp[m-1][n-1]打印出来即可;
代码:
public int uniquePaths(int m, int n) {
//创建数组
int[][] dp = new int[m][n];
//初始化
for (int i = 0; i < n; i++) {
dp[0][i] = 1;
}
for (int i = 0; i < m; i++) {
dp[i][0] = 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];
}
}
// for (int i = 0; i < m; i++) {
// for (int j = 0; j < n; j++) {
// System.out.print(dp[i][j] + " ");
// }
// System.out.println();
// }
//返回结果
return dp[m - 1][n - 1];
}