leetcode python 解题模板
一般的题
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ dic = { "2": "abc", "3": "def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"} res=[] if len(digits) ==0: return res self.dfs(digits, 0, dic, '', res) return res def dfs(self, nums, index, dic, path, res): if index >=len(nums): res.append(path) return string1 =dic[nums[index]] for i in string1: self.dfs(nums, index+1, dic, path + i, res) solution = Solution() print(solution.letterCombinations("23"))
#这个self可以不用传入,不管就行了
涉及到树的题(参考:https://blog.csdn.net/qq_43355165/article/details/122780188)
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# 1. 递归
def mirrorTree_1(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root: return
# tmp = root.left
# root.left = self.mirrorTree(root.right)
# root.right = self.mirrorTree(tmp)
root.left, root.right = self.mirrorTree(root.right), self.mirrorTree_1(root.left)
return root
# 2. 辅助栈
def mirrorTree(self, root):
if not root: return
stack = [root]
while stack:
node = stack.pop()
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
node.left, node.right = node.right, node.left
return root
t1 = TreeNode(
4
)
t2 = TreeNode(
2
)
t3 = TreeNode(
7
)
t4 = TreeNode(
1
)
t5 = TreeNode(
3
)
t6 = TreeNode(
6
)
t7 = TreeNode(
9
)
t2.left = t4
t2.right = t5
t3.left = t6
t3.right = t7
t1.left = t2
t1.right = t3
solution = Solution()
a = solution.mirrorTree(t1)
print(a.__dict__)