115不同的路径 II
题目
http://www.lintcode.com/zh-cn/problem/unique-paths-ii/
“不同的路径” 的跟进问题:
现在考虑网格中有障碍物,那样将会有多少条不同的路径?
网格中的障碍和空位置分别用 1 和 0 来表示。
注意事项
m 和 n 均不超过100
样例
如下所示在3x3的网格中有一个障碍物:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
一共有2条不同的路径从左上角到右下角。
思路
- 可参考114不同的路径
- 第一行或第一列中,若某一位置出现了障碍物,则接下来该行或该列都通不过,特别的如果网格中[0][0]出现障碍物,则路径为0,没法通过障碍物。
- 其他行列中,按着114不同的路径思路,只有当某处出现障碍物时,该地址的路径为0
代码
class Solution:
"""
@param: obstacleGrid: A list of lists of integers
@return: An integer
"""
def uniquePathsWithObstacles(self, obstacleGrid):
# write your code here
#m 行 n 列
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0 for col in range(n)] for row in range(m)]
for i in range(m):
if obstacleGrid[i][0]==1:
dp[i][0]=0
break
else:dp[i][0]=1
for j in range(n):
if obstacleGrid[0][j]==1:
dp[0][j]=0
break
else:dp[0][j]=1
for i in range (1 ,m):
for j in range (1,n):
if obstacleGrid[i][j]==1:
dp[i][j]=0
else:
dp[i][j] = dp[i][j-1] + dp[i-1][j]
return dp[-1][-1]
简约
class Solution:
"""
@param: obstacleGrid: A list of lists of integers
@return: An integer
"""
def uniquePathsWithObstacles(self, obstacleGrid):
# write your code here
#m 行 n 列
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0 for col in range(n)] for row in range(m)]
if obstacleGrid[0][0] == 1:return 0
for i in range (0 ,m):
for j in range (0,n):
if i==0 and j==0: dp[0][0]=1
elif i==0 :
dp[0][j] = (1-obstacleGrid[i][j]) * dp[0][j-1]
elif j==0:
dp[i][0] = (1-obstacleGrid[i][j]) * dp[i-1][0]
else:
dp[i][j] = (1-obstacleGrid[i][j]) * (dp[i][j-1] + dp[i-1][j])
return dp[-1][-1]
112删除排序链表中的重复元素
题目
http://www.lintcode.com/zh-cn/problem/remove-duplicates-from-sorted-list/
给定一个排序链表,删除所有重复的元素每个元素只留下一个。
样例
给出 1->1->2->null,返回 1->2->null
给出 1->1->2->3->3->null,返回 1->2->3->null
思路
- 集合第一个元素是表头,然后判断下一个元素是否在集合中,不在则存进去,存在的话就删除这个元素,直到出现NULL(即is None)
- 此次用到了集合set(),它主要可以减少额外的内存,若用列表的话,会出现内存不足问题。
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: head is the head of the linked list
@return: head of linked list
"""
def deleteDuplicates(self, head):
# write your code here
if head is None:return head
#集合set不会增加额外内存
store = set([head.val])
cur, pre = head.next , head
while cur:
#存在删除
if cur.val in store:
pre.next = cur.next
cur = cur.next
#不在,添加
else:
store.add(cur.val)
pre = pre.next
cur = cur.next
return head