Unique Paths
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.
这道题有三种解法
1.递归算法(暴力)
机器人每次只有两种选择,即向右或向下,所以当前位置的路径条数等于向右一步和向下一步的路径和。
class Solution {
public int uniquePaths(int m, int n) {
if(m == 1 || n == 1)
return 1;
return uniquePaths(m - 1,n) + uniquePaths(m,n - 1);
}
}
显而易见,Leetcode 没有AC这种解法,因为 Time Exceed
2.简化的递归算法(或者动态规划)
尾递归都可以通过建立数组存储之前的值来避免,此处可以建立一个m * n的二维数组,每个位置的值是从起点到达这个位置的路径条数空间复杂度为O(m*n)时间复杂度为O(m * n)
class Solution {
public int uniquePaths(int m, int n) {
int[][] arr = new int[m][n];
for(int i = 0;i < m;i ++)
arr[i][0] = 1;
for(int i = 0;i < n;i ++)
arr[0][i] = 1;
for(int i = 1;i < m;i ++)
for(int j = 1;j < n;j ++)
arr[i][j] = arr[i - 1][j] + arr[i][j - 1];
return arr[m - 1][n - 1];
}
}
动态规划(dp)的想法是:建一个一维数组来存储当前行的路径条数,通过行与行之间的递推关系来解决问题。
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] + res[j - 1];
}
}
return res[n - 1];
}
}
3.纯数学算法(排列组合)
对于机器人来说,总的步数是固定的,向下走向右走的步数也是固定的。唯一不同的就是向下和向右步数的顺序问题。用组合数公式即可求解(代码就不写了)注意n和m用到组合数中应该减一。
组合数公式:c(m,n) = m! / (n! * (m - n)!)
Unique Paths ||
主要是加了障碍物,导致第三种算法失灵。动态规划仍可求解,只要注意障碍物位置和附近位置的关系即可。