[LeetCode] Unique Paths and Unique Paths II

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?

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.

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 is 2.


本文思路:

        起初采用的是递归的思想,但是提交后报错说超时,于是采用动态规划的思想,设置了一个同样大小的二维数组,来保存每个位置的路径数。对于Unique Paths II只需将其中的路障位置的路径数设为0即可。

动态规划主要实现依据:table[m][n]=table[m-1][n]+table[m][n-1],其中table就是保存每个位置路径数的二维数组。

代码实现如下

Unique Paths 

public class Solution {
    public static int uniquePaths(int m, int n) {
        if(m==1||n==1)return 1;
        if(m==0||n==0)return 0;
        int[][] table=new int[m][n];
        table[0][0]=1;
        for(int i=0;i<m;i++){
        	for(int j=0;j<n;j++){
        		if(i==0||j==0)table[i][j]=1;
        		else table[i][j]=table[i-1][j]+table[i][j-1];
        	}
        }
        //int result=getCount(table,m-1,n-1);
        return table[m-1][n-1];
    }
}


Unique Paths II

public class Solution {
     public static int uniquePathsWithObstacles(int[][] obstacleGrid){
    	int m=obstacleGrid.length;
    	int n=obstacleGrid[0].length;
    	if(m==0||n==0)return 0;
    	int[][] table=new int[m][n];//保存每个位置的路径数
    	for(int i=0;i<m;i++){
    		for(int j=0;j<n;j++){
    			if(obstacleGrid[m-i-1][n-j-1]==1)table[i][j]=0;
    			else if(i==0&&j==0&&obstacleGrid[m-i-1][n-j-1]==0)table[i][j]=1;
    			else if(i>0&&j>0){
    				table[i][j]=table[i-1][j]+table[i][j-1];
    			}
    			else if(i>0&&j==0){
    				table[i][j]=table[i-1][j];
    			}
    			else if(i==0&&j>0){
    				table[i][j]=table[i][j-1];
    			}
    		}
    	}
    	//int count=getCount(obstacleGrid,m-1,n-1);
        return table[m-1][n-1];
    }
   
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值