3.31leetcode139. 单词拆分25. K 个一组翻转链表113. 路径总和 II

139. 单词拆分

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

25. K 个一组翻转链表

想清楚其实挺简单的,组内翻转、组间衔接,难点在组间衔接,注意每组头尾翻转,需要做的衔接是上轮新尾接这轮新头,所以每轮开始之前保存上轮新尾,结束之后接上新头。

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

113. 路径总和 II 

 

 

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值