剑指 Offer 34. 二叉树中和为某一值的路径

剑指 Offer 34. 二叉树中和为某一值的路径_List

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
        res = []
        tmpRes = []
        
        #这道题首先考察的是遍历,然后再添加上回溯
        def dfs_backTrack(tmpRoot, target):
            if not tmpRoot:
                return 
            tmpRes.append(tmpRoot.val)
            if not tmpRoot.left and not tmpRoot.right:
                if sum(tmpRes) == target:
                    res.append(tmpRes[:])
            dfs_backTrack(tmpRoot.left, target)
            dfs_backTrack(tmpRoot.right, target)
            tmpRes.pop()
        

        if not root:
            return list()

        dfs_backTrack(root, target)
        return res

剑指 Offer 38. 字符串的排列

剑指 Offer 34. 二叉树中和为某一值的路径_List_02

class Solution:
    def permutation(self, s: str) -> List[str]:
        #最耗时的解法
        res = []
        def back_trace(s, tmp):
            if not s:
                if ''.join(tmp) not in res:
                    res.append(''.join(tmp))
                return 0
            for i in range(len(s)):
                back_trace(s[:i]+s[i+1:], tmp+[s[i]])

        back_trace(s, [])
        return res


        #官方解法
        cList, res = list(s), []
        def dfs(idx):
            if idx == len(cList) - 1:
                res.append(''.join(cList))
                return 
            dic = set()
            for i in range(idx, len(cList)):
                if cList[i] in dic: continue
                dic.add(cList[i])
                cList[i], cList[idx] = cList[idx], cList[i]
                dfs(idx+1)
                cList[i], cList[idx] = cList[idx], cList[i]
        dfs(0)
        return res