一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
问总共有多少条不同的路径?
Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right
解题思路:
动态规划问题:
用一个m*n的数组A保存从左上角到此为止的结果,数组A的第一行和第一列的值都赋为一,其他位置A[X][Y]=A[X-1][Y]+A[X][Y-1],所求的结果就是A[m-1][n-1].
public static int uniquePaths1(int m, int n) {
Integer[][] map = new Integer[m][n];
for(int i = 0; i<m;i++){
map[i][0] = 1;
}
for(int j= 0;j<n;j++){
map[0][j]=1;
}
for(int i = 1;i<m;i++){
for(int j = 1;j<n;j++){
map[i][j] = map[i-1][j]+map[i][j-1];
}
}
return map[m-1][n-1];
}