Leetcode 之 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?

题目就是找m * n方格从左上方到右下方的有多少种不同的路径,开始用组合数学做,就是C(m-1)_(m+n-2),很好写,但是由于分子分母乘的时候太大,会出现溢出的情况,所以WA。

后来就转换成DP,其实这是一个比较标准的DP问题。状态就是当前坐标下有几种路径,即d(i,j)。转移方程也比较好想:d(i,j)=d(i,j-1)+d(i+1,j)。

所以建立一个m*n的数组,把每个路径数都存到数组里面,这样只需要求d(m,n)就行了。

注意,要把第1行和第1列先进行初始化,都变成1,表示一直往右走或者一直往下走。另外,还考虑m或者n为0的情况(不晓得有没有用例,边界条件直接加上了)。

 public int uniquePaths(int m, int n) {
         if(m == 0 || n == 0)   return 0;
         int[][] array = new int[m][n];
         array[0][0] = 1;

         for(int i = 1;i < m;i++){
             array[i][0] = 1;
         }
         for(int i = 1;i < n;i++){
             array[0][i] = 1;
         }
         for(int i = 1;i < m;i++){
             for(int j = 1;j < n;j++){
                 array[i][j] = array[i - 1][j] + array[i][j - 1];
             }
         }
         return array[m - 1][n - 1];
     }

61 / 61 test cases passed.
Status: Accepted
Runtime: 212 ms

接下来上Unique Paths II
Follow up for “Unique Paths”:

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

也就是说,有一个障碍物数组加进来,标1的格子是过不去的。其实跟I一样,用动态规划生成表,只不过在循环的时候加入对障碍物的判断,如果有障碍物的话,表中填0,表示这个格子有0条路径,否则还是用之前的传递函数。

这里注意最上角的位置不能通过计算,应该通过赋值得到。

    int[][] array;


    public int uniquePathsWithObstacles(int[][] obstacleGrid) {

     int m = obstacleGrid.length;
     int n = obstacleGrid[0].length;

     array = new int[m][n];

         for(int i = 0;i < m;i++){
             for(int j = 0;j < n;j++){
                 if(obstacleGrid[i][j] == 1){
                     array[i][j] = 0;
                 }
                 else if(i == 0 && j == 0){
                     array[i][j] = 1;
                 }
                 else{
                     array[i][j] = d(i - 1,j) + d(i, j - 1);
                 }
             }
         }
         return array[m - 1][n - 1];

    }

    public int d(int i, int j){
        if(i >= 0 && j >= 0){
            return array[i][j];
        }
        else{
            return 0;
        }
    }

43 / 43 test cases passed.
Status: Accepted
Runtime: 340 ms

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值