1.1不同路径
在二维网格 grid 上,有 4 种类型的方格:
1
表示起始方格。且只有一个起始方格。
2
表示结束方格,且只有一个结束方格。
0
表示我们可以走过的空方格。
-1
表示我们无法跨越的障碍。
返回在四个方向(上、下、左、右)上行走时,从起始方格到结束方格的不同路径的数目,要求
每一个无障碍方格都要通过一次,但是一条路径中不能重复通过同一个方格。
回朔法
一种选优搜索法,又称为试探法,但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”
def uniquePath(self,grid):
r,c=len(grid),len(grid[0])
si,sj,n=0,0,0
for i in range(r):
for j in range(c):
if grid[i][j]==0:
n+=1
elif grid[i][j]==1:
n+=1
si,sj=i,j
#确定要经过的点的个数和起始点的位置(si,sj)
def dfs(i,j,n):
if grid[i][j]==2: #起始点就是终点
if n==0:
return 1
t=grid[i][j]
grid[i][j]=-1
res=0
for di,dj in [[-1,0],[1.0],[0,-1],[0,1]]:#向四个方向移动
ni,nj=i+di,j+dj
if 0<=ni<r and 0<=nj<c and grid[ni][nj] in [0,2]: #没有到达边界并且值是0或者2的时候反向探索
res+=dfs(ni,nj,n-1)
grid[i][j]=t
return res
return dfs(si,sj,n)
1.2合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
x
=
{
l
1
[
0
]
+
m
e
r
g
e
(
l
1
[
1
:
]
,
l
2
)
if
l
1
[
0
]
<
l
2
[
0
]
l
2
[
0
]
+
m
e
r
g
e
(
l
1
,
l
2
[
1
:
]
)
else
x = \begin{cases} l1[0]+merge(l1[1:],l2) &\text{if } l1[0]<l2[0] \\ l2[0]+merge(l1,l2[1:]) &\text{else} \end{cases}
x={l1[0]+merge(l1[1:],l2)l2[0]+merge(l1,l2[1:])if l1[0]<l2[0]else
递归
class Node:
def __init__(self,val):
self.val=val
self.next=None
class LinkList:
def __init__(self):
self.head=None
def add(self,val): #头插法实现链表
new_node=Node(val)
new_node.next=self.head
self.head=new_node
def printLinkList(self):
curent=self.head
while curent:
print(f"{curent.val}", end="")
curent=curent.next
class question1:
def mergeTwoLists(self,l1,l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val<l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2
def test():
q = question1()
l1 = LinkList()
l1.add(3)
l1.add(2)
l1.add(1)
l2 = LinkList()
l2.add(5)
l2.add(3)
l2.add(1)
result=LinkList()
result.head=q.mergeTwoLists(l1.head,l2.head)
result.printLinkList()
test()