[LeetCode]--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.
The total number of unique paths is 2.
尋求最短路徑,從左上走到右下,保證每次只能往左走或往下走(不可以斜著走)。其中數(shù)字1是障礙,表示“此路不通”,求總共的路線數(shù)。
第一種二維數(shù)組
用一個(gè)二維數(shù)組來表示前者的路徑
核心就是這個(gè),如果不等于1,我們就找到前者的路徑相加。
第二種一維數(shù)組
其實(shí)一維數(shù)組足以表示前者的路徑,因?yàn)橐痪S數(shù)組左邊是你更新過的,右邊是沒更新,沒更新的相當(dāng)于上一排,也就是上一排的來路加上左邊的來路之和就是現(xiàn)在的來路。(解釋好混亂,但我是這樣想就理解了)
public int uniquePathsWithObstacles(int[][] obstacleGrid) {if (obstacleGrid[0][0] == 1)return 0;int m = obstacleGrid.length;int n = obstacleGrid[0].length;int[] step = new int[n];step[0] = 1;for (int i = 0; i < m; i++)for (int j = 0; j < n; j++) {if (obstacleGrid[i][j] == 1)step[j] = 0;else if (j > 0)step[j] += step[j - 1];}return step[n - 1];} 與50位技術(shù)專家面對面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的[LeetCode]--63. Unique Paths II的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 自定义特性
- 下一篇: php : RBAC 基于角色的用户权限