【LeetCode】63. Unique Paths II

题目:

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).

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.

Note: m and n will be at most 100.

Example 1:

Input:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

 

描述 :

给出一副地图,起始在左上角,终点在右下角,图中的1表示障碍物,每次只能移动一步,

请问到达终点一共有多少种不同的路径

 

分析:

可以采用dfs搜索遍历所有路径,但是超时了...

可能有多项式级别的解法...

借鉴了大神的做法,用动态规划思想...

对于可到达的位置,到达该位置的路径条数等于到达上侧的路径数和到达其左侧的路径数之和,

这也就是DP的递推公式,过程见代码二

 

但是竟然一直过不了,显示超出int的表示范围,结果,把cnt声明成long型,竟然过了......

第一次在某个平台发现 long 和 int 表示范围不一样...

测试发现,在leetcode里 long是8个字节,int是4个字节....

 

代码一:(指数级别时间复杂度,超时)

class Solution {
public:
	int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
		int n = obstacleGrid.size();
		if (!n) {
			return 0;
		}
		int m = obstacleGrid[0].size();
		
		int result = 0;
		dfs(obstacleGrid, 0, 0, result);
		return result;
	}
	
	void dfs(const vector<vector<int>>& map, int x, int y, int &result) {
		int n = map.size(), m = map[0].size();
		if (x >= n || y >= m || map[x][y]) {
			return;
		}
		if (x == n - 1 && y >= m - 1) {
			++ result;
			return;
		}
		dfs(map, x + 1, y, result);
		dfs(map, x, y + 1, result);
	}
	
};

代码二:(时间和空间复杂度均为 O(n^2),有优化空间)

class Solution {
public:
	int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
		int n = obstacleGrid.size();
		if (!n) {
			return 0;
		}
		int m = obstacleGrid[0].size();
		
		vector<vector<long>> cnt;
		
		for (int i = 0; i < n; ++ i) {
			vector<long> row;
			int top = 0;
			if (i == 0) {
				if (!obstacleGrid[i][0]) {
					top = 1;
				}
			} else {
				if (!obstacleGrid[i][0]) {
					top = cnt[i - 1][0];
				}
			}
			row.push_back(top);//每行第一个数
			
			for (int j = 1; j < m; ++ j) {
				int temp = 0;
				if (i) {
					temp += cnt[i - 1][j];
				}
				temp += row[j - 1];
				
				if (obstacleGrid[i][j]) {
					temp = 0;
				}
				row.push_back(temp);
			}
			cnt.push_back(row);
		}
		return cnt[n - 1][m - 1];
	}
	
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值