Leetcode刷题第九天-回溯
113:路径总和II
链接:113. 路径总和 II - 力扣(LeetCode)
root=[-2,null,-3],targetSum=-5莫要忘记负数情况😓
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, val=0, left=None, right=None): 4 # self.val = val 5 # self.left = left 6 # self.right = right 7 class Solution: 8 def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: 9 if(not root ): return [] 10 re=[] 11 self.backtracking(root,targetSum,0,re,[]) 12 return re 13 def backtracking(self,cur,targetSum,sums,re,path): 14 if(not cur): return 15 if(not cur.right and not cur.left): 16 sums+=cur.val 17 path.append(cur.val) 18 if(sums==targetSum): re.append(path[:]) 19 sums-=cur.val 20 path.pop() 21 return 22 sums+=cur.val 23 path.append(cur.val) 24 self.backtracking(cur.left,targetSum,sums,re,path) 25 self.backtracking(cur.right,targetSum,sums,re,path) 26 path.pop() 27 sums-=cur.val
140:单词拆分II
链接:140. 单词拆分 II - 力扣(LeetCode)
💕还得是我妹妹,得高人指点,换个思路😍
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution: 2 def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: 3 if(not s): return[] 4 re=[] 5 self.backtracking(s, wordDict,"",re) 6 return re 7 def backtracking(self,s,wordDict,path,re): 8 if(not s): 9 re.append(path[:len(path)-1]) 10 return 11 for i in range(len(s)): 12 if(s[:i+1] in wordDict): 13 self.backtracking(s[i+1:],wordDict,path+s[:i+1]+" ",re)
明天继续~~~~