DFS+回溯专题11 - leetcode257. Binary Tree Paths/93. Restore IP Addresses

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/84957671

257. Binary Tree Paths

题目描述

给定二叉树,返回所有根节点-叶节点路径。

例子

257

思想
截止条件:到达叶节点(not root.left and not root.right)

解法

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if not root:
            return []
        res = []
        self.dfs(root, str(root.val), res)
        return res
    
    def dfs(self, root, temp, res):
        if not root.left and not root.right:
            res.append(temp)
            return
        if root.left:
            self.dfs(root.left, temp + '->' + str(root.left.val), res)
        if root.right:
            self.dfs(root.right, temp + '->' + str(root.right.val), res)

精简

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if not root:
            return []
        if not root.left and not root.right:
            return [str(root.val)]
        paths = self.binaryTreePaths(root.left) + self.binaryTreePaths(root.right)
        return [str(root.val) + '->' + path for path in paths]

93. Restore IP Addresses

题目描述

给定只包含数字的字符串,返回所有可能有效的IP地址组合。

例子

Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]

思想

合法的IP地址由四个0到255的整数组成。且多个数字时要注意首位不能为0,因为01.0.0.0 这样的IP是不符合规范的。

每位可能的数字位数是1-3位。所以,遍历所有可能的位数(1位、2位、3位且不超过255)。
[截止条件]:刚好遍历完,且4位,存储;到达4位但没有遍历完,直接return。

解法

class Solution(object):
    def restoreIpAddresses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        res = []
        self.dfs(s, [], res)
        return res
        
    def dfs(self, s, temp, res):
        if not s:
            if len(temp) == 4:
                res.append('.'.join(temp))
            return
        if len(temp) == 4:
            return
        
        self.dfs(s[1:], temp + [s[0]], res)
        if s[0] != '0':
            if len(s) >= 2:
                self.dfs(s[2:], temp + [s[:2]], res)
            if len(s) >= 3 and int(s[:3]) <= 255:
                self.dfs(s[3:], temp + [s[:3]], res)

猜你喜欢

转载自blog.csdn.net/a786150017/article/details/84957671