您的位置:首页 > 产品设计 > UI/UE

Leetcode 动态规划 Unique Paths II

2014-08-29 14:46 393 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Unique Paths II

 Total Accepted: 13655 Total
Submissions: 49081My 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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: