LeetCode 63. Unique Paths II

问题描述

这里写图片描述

问题分析

代码实现

  • 递归(TLE)
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0] == null || obstacleGrid[0].length == 0) {
            return 0;
        }
        return findPaths(obstacleGrid, 0, 0);
    }

    public int findPaths(int[][] obstacleGrid, int i, int j) {
        if (i == obstacleGrid.length || j == obstacleGrid[0].length || obstacleGrid[i][j] == 1) {
            return 0;
        }
        if (i == obstacleGrid.length - 1 && j == obstacleGrid[0].length - 1) {
            return 1;
        }
        return findPaths(obstacleGrid, i + 1, j) + findPaths(obstacleGrid, i, j + 1);
    }
  • 动态规划
     public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0] == null || obstacleGrid[0].length == 0) {
            return 0;
        }
         int row = obstacleGrid.length;
         int col = obstacleGrid[0].length;
        int[][] dp = new int[row][col];
         dp[row - 1][col - 1] = obstacleGrid[row - 1][col - 1] == 1 ? 0 : 1;
         for (int j = col - 2; j >= 0; --j) {
             dp[row - 1][j] = obstacleGrid[row - 1][j] == 1 ? 0 : dp[row - 1][j + 1];
         }
         for (int i = row - 2; i >= 0; --i) {
             dp[i][col - 1] = obstacleGrid[i][col - 1] == 1 ? 0 : dp[i + 1][col - 1];
             for (int j = col - 2; j >= 0; --j) {
                 dp[i][j] = obstacleGrid[i][j] == 1 ? 0 : dp[i + 1][j] + dp[i][j + 1];
             }
         }
         return dp[0][0];
     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值