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?

Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Solution1: recursion 代码如下,但是放在leetCode上跑会超时。public class Solution {
public int uniquePaths(int m, int n) {
return recPaths(m, n, 1, 1);
}
public int recPaths(int m, int n, int row, int col) {
if(m == 1 || n == 1)
return 1;
else if(row > m || col > n)
return 0;
else {
return recPaths(m, n, row + 1, col) + recPaths(m, n, row, col + 1);
}
}
}
Solution2: dynamic programming
递推式是res[i][j]=res[i-1][j]+res[i][j-1],这样我们就可以用一个数组来保存历史信息,也就是在i行j列的路径数,这样每次就不需要重复计算,从而降低复杂度。用动态规划我们只需要对所有格子进行扫描一次,到了最后一个得到的结果就是总的路径数,所以时间复杂度是O(m*n)。而对于空间可以看出我们每次只需要用到上一行当前列,以及前一列当前行的信息,我们只需要用一个一维数组存上一行的信息即可,然后扫过来依次更替掉上一行对应列的信息即可(因为所需要用到的信息都还没被更替掉),所以空间复杂度是O(n).
public class Solution {
public int uniquePaths(int m, int n) {
if(m <= 0 || n <= 0)
return 0;
int[] res = new int[n];
res[0] = 1;
for(int i = 0; i < m; i++) {
for(int j = 1; j < n; j++) {
res[j] += res[j - 1];
}
}
return res[n - 1];
}
}
Or 二维数组保存信息:
public class Solution {
public int uniquePaths(int m, int n) {
int dp[][] = new int[m][n];
for(int i = 0; i < m; i++)
dp[i][0] = 1;
for(int j = 0; j < n; j++)
dp[0][j] = 1;
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
}
}
return dp[m - 1][n - 1];
}
}

No comments:
Post a Comment