Leetcode 动态规划 Unique Paths II

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Unique Paths II

  Total Accepted: 13655  Total Submissions: 49081 My Submissions

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.

Note: m and n will be at most 100.





题意:给定一个 m * n 的网格,网格中1表示障碍,不可走;0表示可走。
一个机器人要从左上角走到右下角,每次只能向下或向右移动一个位置,
问有多少种走法
思路1:记忆化搜索
使用一个两维 paths[i][j]记录 (i,j)到(m,n)的路径数
先把 paths 数组里的所有元素都置为 -1,表示之前没有搜索过(i,j)到(m,n)的路径
再把 obstacleGrid[i][j] 数组里为 1的对应 paths[i][j] 转为 0,表示从(i,j)到不了(m,n)
用 dfs 去枚举各种可能的路径情况
复杂度:时间 O(2^n) 空间O(n)


思路2:dp
用 f[i][j] 表示从 (0,0)到 (i, j)的路径数,则状态转移方程为
f[i][j] = f[i - 1][j] + f[i][j - 1]
实现的时候,可以只用一个一维的数组paths[j]表示外循环第i次迭代内循环第j次迭代对应的paths值
在还没更新状态时,paths[j]对应f[i - 1][j]; paths[j - 1]对应f[i][j - 1]
复杂度:时间 O(n),空间O(n)

int paths[101][101];
int mm, nn;
int dfs(int x, int y){
	if(x >= mm || y >= nn) return 0;
	if(paths[x][y] >= 0) return paths[x][y];
	if(x == mm - 1 && y == nn - 1) return 1;
	return paths[x][y] = dfs(x + 1, y) + dfs(x, y + 1);
}
int uniquePathsWithObstacles(vector<vector<int> >&obstacleGrid){
	mm = obstacleGrid.size(), nn = obstacleGrid[0].size();
	memset(paths, -1, sizeof(paths));
	for(unsigned int i = 0; i < obstacleGrid.size(); ++i)
		for(unsigned int j = 0; j < obstacleGrid[0].size(); ++j){
			if(obstacleGrid[i][j] == 1) paths[i][j] = 0;
		}
	return dfs(0, 0);
}




int paths[101];
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid){
	memset(paths, 0, sizeof(paths));
	int m = obstacleGrid.size(), n = obstacleGrid[0].size();
	if(obstacleGrid[0][0] || obstacleGrid[m- 1][n - 1]) return 0;
	paths[0] = obstacleGrid[0][0] ? 0 : 1;
	for(int i = 0 ; i < m; ++i){
		for(int j = 0; j < n; ++j){
			if(obstacleGrid[i][j] ) paths[j] = 0; 
			else paths[j] = obstacleGrid[i][j] ? 0 : ( j == 0 ? 0: paths[j - 1]) + paths[j];
		}
	}
	return paths[n - 1];
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值