摘要:和完全一樣的做法,只要在初始化首行和首列遇到時(shí)置零且即可。對(duì)了,數(shù)組其它元素遇到也要置零喏,不過(guò)就不要啦。
Problem
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.
Noticem and n will be at most 100.
ExampleFor 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和Unique Path完全一樣的做法,只要在初始化首行和首列遇到obstacle時(shí)置零且break即可。對(duì)了,數(shù)組其它元素遇到obstacle也要置零喏,不過(guò)就不要break啦。
Solution二維DP
public class Solution { public int uniquePathsWithObstacles(int[][] A) { int m = A.length, n = A[0].length; int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { if (A[i][0] == 0) dp[i][0] = 1; else break; } for (int j = 0; j < n; j++) { if (A[0][j] == 0) dp[0][j] = 1; else break; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (A[i][j] == 0) dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } }
一維DP
public class Solution { public int uniquePathsWithObstacles(int[][] A) { int n = A[0].length; int[] dp = new int[n]; dp[0] = 1; for (int i = 0; i < A.length; i++) { for (int j = 0; j < n; j++) { if (A[i][j] == 1) dp[j] = 0; else if (j > 0) dp[j] += dp[j-1]; } } return dp[n-1]; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/65791.html
摘要:簡(jiǎn)單的動(dòng)規(guī)題目,建立數(shù)組。坐標(biāo)為矩陣的坐標(biāo),值為從左上角到這一格的走法總數(shù)。賦初值,最上一行和最左列的所有格子的走法都只有一種,其余格子的走法等于其左邊格子走法與上方格子走法之和。最后,返回即可。 Problem A robot is located at the top-left corner of a m x n grid (marked Start in the diagram ...
摘要:和唯一的不同是組合中不能存在重復(fù)的元素,因此,在遞歸時(shí)將初始位即可。 Combination Sum I Problem Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T...
摘要:先想到的是,其實(shí)也可以,只是需要在遍歷的時(shí)候,添加到數(shù)組中的數(shù)要掉,略微麻煩了一點(diǎn)。在里跑的時(shí)候,也要快一點(diǎn)。另一種類似做法的就快的多了。如果是找出所有包括重復(fù)的截距呢 Problem Given two arrays, write a function to compute their intersection. Notice Each element in the result m...
摘要:整個(gè)過(guò)程相當(dāng)于,直接在和里去掉既是又是的。所以最后返回的,一定是只出現(xiàn)過(guò)一次的,而出現(xiàn)兩次的都在里,出現(xiàn)三次的都被消去了。 Single Number I Problem Given 2*n + 1 numbers, every numbers occurs twice except one, find it. Example Given [1,2,2,1,3,4,3], return...
Subsets Problem Given a set of distinct integers, return all possible subsets. Notice Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets. Example ...
閱讀 2112·2023-04-26 00:41
閱讀 1142·2021-09-24 10:34
閱讀 3573·2021-09-23 11:21
閱讀 4031·2021-09-22 15:06
閱讀 1557·2019-08-30 15:55
閱讀 898·2019-08-30 15:54
閱讀 1829·2019-08-30 15:48
閱讀 550·2019-08-29 13:58