动态规划——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 as1and0respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is2.

Note: m and n will be at most 100.

递归例程:
public class Solution {
    public int uniquePathsWithObstacles(int[][] grid) {
        if(grid == null||grid.length == 0||grid[0].length == 0)
            return 0;
        int row=grid.length;
        int col=grid[0].length;
        return help(grid,0,0,row,col);
    }
    public int help(int[][] grid,int i,int j,int row,int col)
        {
        if(i == row-1&&j == col-1)
            return 1;
        if(grid[i][j] == 1)
            return 0;
        if(i == row-1)
            return help(grid,i,j+1,row,col);
        if(j == col-1)
            return help(grid,i+1,j,row,col);
        else
            return help(grid,i+1,j,row,col)+help(grid,i,j+1,row,col);
    }
}


DP例程:
 public int uniquePathsWithObstacles(int[][] grid) {
        if(grid == null||grid.length == 0||grid[0].length == 0)
            return 0;
        int row=grid.length;
        int col=grid[0].length;
        int[][] dp=new int[row][col];
        dp[row-1][col-1]=1;
        if(grid[row-1][col-1] == 1)
            dp[row-1][col-1]=0;
        //最下行初始化
        for(int j=col-2;j>=0;j--)
            {
            if(grid[row-1][j] == 1)
                dp[row-1][j]=0;
            else
                dp[row-1][j]=dp[row-1][j+1];
        }
        //最右行初始化
        for(int i=row-2;i>=0;i--)
            {
            if(grid[i][col-1] == 1)
                dp[i][col-1]=0;
            else
                dp[i][col-1]=dp[i+1][col-1];
        }
        //general
        for(int i=row-2;i>=0;i--)
            {
            for(int j=col-2;j>=0;j--)
                {
                if(grid[i][j] == 1)
                    dp[i][j]=0;
                else
                    dp[i][j]=dp[i+1][j]+dp[i][j+1];
            }
        }
        return dp[0][0];
    }


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值