894.所有可能的满二叉树
https://leetcode-cn.com/problems/all-possible-full-binary-trees/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
memo = {0: [],1:[TreeNode(0)]}
def allPossibleFBT(self, N: int) -> List[TreeNode]:
if N not in Solution.memo:
ans = []
for x in range(N):
y = N - 1 -x
for left in self.allPossibleFBT(x):
for right in self.allPossibleFBT(y):
bns = TreeNode(0)
bns.left = left
bns.right = right
ans.append(bns)
Solution.memo[N]=ans
return Solution.memo[N]
32.最长有效括号
https://leetcode-cn.com/problems/longest-valid-parentheses/
class Solution:
def longestValidParentheses(self, s: str) -> int:
ans = 0
dp = [0] * len(s)
for i in range(1,len(s)):
if s[i] == ")":
if s[i-1] == "(":
dp[i] = (dp[i-2] if i >= 2 else 0) + 2
elif i - dp[i-1] > 0 and s[i-dp[i-1]-1] == "(":
dp[i] = dp[i-1] + (dp[i - dp[i-1] - 2] if i - dp[i-1] >= 2 else 0) + 2
ans = max(ans,dp[i])
return ans
3.无重复的最长子串
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
ans = 0
i = 0 # 第一个指针
char_dict = {}
for j in range(len(s)):
if s[j] in char_dict.keys():
i = max(char_dict[s[j]],i)
ans = max(ans, j- i + 1)
char_dict[s[j]] = j+1
return ans