leetcode 【 Unique Paths II 】 python 实现
2015-01-26 16:12
323 查看
题目:
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
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
The total number of unique paths is
Note: m and n will be at most 100.
代码:oj测试通过 Runtime: 48 ms
思路:
思路模仿Unique Path这道题:
/article/5261261.html
只不过多了某些障碍点;针对障碍点,加一个判断条件即可:如果遇上障碍点,那么到途径这个障碍点到达终点的可能路径数为0。然后继续迭代到尾部即可。
个人感觉40行的python脚本不够简洁,总是把special case等单独拎出来。后面再练习代码的时候,考虑如何让代码更简洁。
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
1and
0respectively 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.
代码:oj测试通过 Runtime: 48 ms
class Solution: # @param obstacleGrid, a list of lists of integers # @return an integer def uniquePathsWithObstacles(self, obstacleGrid): # ROW & COL ROW = len(obstacleGrid) COL = len(obstacleGrid[0]) # one row case if ROW==1: for i in range(COL): if obstacleGrid[0][i]==1: return 0 return 1 # one column case if COL==1: for i in range(ROW): if obstacleGrid[i][0]==1: return 0 return 1 # visit normal case dp = [[0 for i in range(COL)] for i in range(ROW)] for i in range(COL): if obstacleGrid[0][i]!=1: dp[0][i]=1 else: break for i in range(ROW): if obstacleGrid[i][0]!=1: dp[i][0]=1 else: break # iterator the other nodes for row in range(1,ROW): for col in range(1,COL): if obstacleGrid[row][col]==1: dp[row][col]=0 else: dp[row][col]=dp[row-1][col]+dp[row][col-1] return dp[ROW-1][COL-1]
思路:
思路模仿Unique Path这道题:
/article/5261261.html
只不过多了某些障碍点;针对障碍点,加一个判断条件即可:如果遇上障碍点,那么到途径这个障碍点到达终点的可能路径数为0。然后继续迭代到尾部即可。
个人感觉40行的python脚本不够简洁,总是把special case等单独拎出来。后面再练习代码的时候,考虑如何让代码更简洁。
相关文章推荐
- [LeetCode]Unique Paths II@python
- LeetCode-63-Unique Paths II(C语言实现)
- [LeetCode]题解(python):063-Unique Paths II
- LeetCode 63 — Unique Paths II(C++ Java Python)
- LeetCode 95 Unique Binary Search Tree II(Python详解及实现)
- 【LeetCode-面试算法经典-Java实现】【063-Unique Paths II(唯一路径问题II)】
- 【LeetCode-面试算法经典-Java实现】【063-Unique Paths II(唯一路径问题II)】
- 【Leetcode】【python】Unique Paths/Unique Paths II
- [leetcode]Unique Paths II @ Python
- LeetCode : Unique Paths II
- [leetcode刷题系列]Unique Paths II
- Unique Paths II 求在矩阵里从左上走到右下的总方法数(有障碍)@LeetCode
- LeetCode:Unique Paths II
- LeetCode 63: Unique Paths II
- leetcode -- Unique Paths II
- Unique Paths II [LeetCode]
- leetcode - Unique Paths II
- [LeetCode]Unique Paths I & II
- [Leetcode] Unique Paths II
- [leetcode]Unique Paths II