class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
tmp = ''
slen = len(s)
cur = 0
dp = slen*[0] #1表示该处结束可以拆分
dp1i = [-1]
for cur in range(slen):
tmp += s[cur]
for i in dp1i:
i+=1
if s[i:cur+1] in wordDict:
dp[cur]=1
dp1i.append(cur)
tmp = ''
break
if dp[-1]==1:return True
else:return False
想清楚其实挺简单的,组内翻转、组间衔接,难点在组间衔接,注意每组头尾翻转,需要做的衔接是上轮新尾接这轮新头,所以每轮开始之前保存上轮新尾,结束之后接上新头。
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head:return
if k==1:return head
cur = head
llen = 0
while cur is not None:
llen=llen+1
cur = cur.next
times = llen//k
cur = head
last_rear=None
this_head=None
for j in range(times):
last_rear = this_head#前尾
this_head = cur#本次的原头,下轮做前尾
next_head = cur
for q in range(k):
next_head = next_head.next#下轮的原头
#开始翻转,cur指向本次的原头
pre = cur
cur = cur.next
pre.next = None
while cur != next_head:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
#此时pre指向本轮新头
if j == 0:headnew=pre
#反转结束之后需要前尾->新头
if last_rear:
last_rear.next = pre
#结束时cur指向最后一轮头
this_head.next = cur
return headnew
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:return
dic = {1:0}
res=[]
parent = {root:1}
def dfs(root):
dic[root]=dic[parent[root]]+root.val
if root.left:
parent[root.left]=root
dfs(root.left)
if root.right:
parent[root.right]=root
dfs(root.right)
if not root.left and not root.right and dic[root]==targetSum:
tmp = []
cur = root
while cur!=1:
tmp.append(cur.val)
cur = parent[cur]
tmp.reverse()
res.append(tmp)
dfs(root)
return res