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

Unique Paths II

2017-05-15 22:41 148 查看
原题地址:点我传送

一道动态规划的题目,看到一个花了挺长时间解决的算法,就是用数组ans[m]来记录按行(i)遍历时每一行当前对应的那个点(i,j)所拥有的经过路径。如果是1(障碍)则为0,否则它是它上面那个点所拥有的路径(ans[j],此时未更新)+它左边那个点的路径(ans[i-1])。最后的ans[m-1]就是计算到最后一行时最后一列的那个点(即终点)的答案。

原解释:

let's take out the obstacles for now, let's go to #62, when you solve it by 2 dimension dp, let's say you have with a 4x3 array, you start like

0 0 0 0

0 0 0 0

0 0 0 0

and then you go row by row or column by column adding what's not already solved, let's choose row by row, first row will be all 1s, like

1 1 1 1

0 0 0 0

0 0 0 0

then you start the second row and you add the count of paths on the top and the count in the left, so the evolution will look like

1 1 1 1

1 0 0 0

0 0 0 0

1 1 1 1

1 2 0 0

0 0 0 0

1 1 1 1

1 2 3 0

0 0 0 0

1 1 1 1

1 2 3 4

0 0 0 0

now let's go to the third row, it's the same, I'll put the example here, but note that for the 3rd row, you only care about the second row, line 1 is too old already

1 1 1 1

1 2 3 4

1 0 0 0

1 1 1 1

1 2 3 4

1 3 0 0

1 1 1 1

1 2 3 4

1 3 6 0

1 1 1 1

1 2 3 4

1 3 6 10

The same will happen with any row, you just care about the previous one, the rest are forgotten, so you don't need to store them.

What about columns? it's the same, when you are in any column, you only care about the previous one IN THE SAME ROW, so it's ok to modify your only stored row, as, again, you don't care about older columns even in the previous row.

对应的之前比较简单的Unique Paths I也可以用类似的方法做。

Java:

public class Solution
9700
{
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length;
int m = obstacleGrid[0].length;
int ans[]= new int[m];
ans[0] = 1;
for (int i = 0 ; i < n ;i++)
{
for (int j = 0; j < m; j++)
{
if (obstacleGrid[i][j] == 1)
{
ans[j] = 0;
}
else if (j > 0)
{
ans[j] += ans[j - 1];
}
}
}
return ans[m - 1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: