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

63. Unique Paths II 等题

2016-11-23 12:25 429 查看

62. 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?



Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

题解:

在坐标为(i,j)的格子上,有两种选择,向左或向下走:

如果向左走,则到(i,j-1)位置,就有该位置的x种走法到终点;

如果向下走,则到(i-1,j)位置,有该位置的y种走法。

所以用
f(x,y)
表示从(x,y)到终点有几种走法,有:

f(x,y) = f(x-1,y) + f(x,y-1)


所以从f(1,1)开始递推,先处理边界处(全部为1,走直线),再递推到终点,就得到答案了。

代码:

class Solution {
public:
int uniquePaths(int m, int n) {
if(!(m&&n)) {
return 0;
}
vector<vector<int>> f(m+1, vector<int>(n+1));

f[1][1] = 0;
for(int i=1; i<=m; ++i) {
f[i][1] = 1;
}

for(int i=1; i<=n; ++i) {
f[1][i] = 1;
}

for(int i=2; i<=m; ++i) {
for(int j=2; j<=n; ++j) {
f[i][j] = f[i-1][j] + f[i][j-1];
}
}

// for(int i=0; i<=m; ++i) {
//     for(int j=0; j<=n; ++j) {
//         cout << f[i][j] << " ";
//     }
//     cout << endl;
// }

return f[m]
;
}
};


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

Note: m and n will be at most 100.

题解:

和上一题要求相同,不过这次地图上出现“障碍物”。注意到两点:

1. 在递推的过程中,如果当前位置是障碍物,那么就有0种方式走。

2. 从起点到终点的路径数,和从终点到起点的数量相同。

因此,用上一题的递推思路,特殊处理边界(与上一个点的路径数相同,0或1),再从f(2,2)开始递推到终点。

代码:

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& G) {
int m=G.size();
if(!m) return 0;
int n=G[0].size();
if(!n) return 0;

vector<vector<int>> f(m+1, vector<int>(n+1));

f[1][1] = !G[0][0];

for(int i=2; i<=m; ++i) {
f[i][1] = f[i-1][1] & !G[i-1][0];
}

for(int i=2; i<=n; ++i) {
f[1][i] = f[1][i-1] & !G[0][i-1];
}

for(int i=2; i<=m; ++i) {
for(int j=2; j<=n; ++j) {
f[i][j] = G[i-1][j-1]? 0: f[i-1][j] + f[i][j-1];
}
}

// for(int i=0; i<=m; ++i) {
//     for(int j=0; j<=n; ++j) {
//         cout << f[i][j] << " ";
//     }
//     cout << endl;
// }

return f[m]
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode