文章目录
- [82. 删除排序链表中的重复元素 II](https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/)
- [117. 填充每个节点的下一个右侧节点指针 II](https://leetcode.cn/problems/populating-next-right-pointers-in-each-node-ii/)
- [97. 交错字符串](https://leetcode.cn/problems/interleaving-string/)
- [89. 格雷编码](https://leetcode.cn/problems/gray-code/)
82. 删除排序链表中的重复元素 II
懒得想了…直接全放到数组中去重,然后重新构建了
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
ls=[]
p=head
while p!=None:
ls.append(p.val)
p=p.next
s=set()
nums=[]
for num in ls:
if num in s:
nums.append(num)
s.add(num)
ls=set(ls)
print(ls)
for num in nums:
ls.discard(num)
dumphead=ListNode(-999)
p=dumphead
for num in sorted(list(ls)):
p.next=ListNode(num)
p=p.next
return dumphead.next
117. 填充每个节点的下一个右侧节点指针 II
用层次遍历即可
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
if root==None:
return root
ls=[root]
while len(ls)!=0:
new_ls=[]
for node in ls:
if node.left!=None:
new_ls.append(node.left)
if node.right!=None:
new_ls.append(node.right)
for index in range(len(new_ls)):
if index==len(new_ls)-1:
new_ls[index].next=None
else:
new_ls[index].next = new_ls[index+1]
ls=new_ls
return root
97. 交错字符串
太nb了!直接用python自带的记忆化存储
用超好写的递归
class Solution:
@cache
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s2)==0 or len(s1)==0:
return s3==s1+s2
if len(s3)!=len(s1)+len(s2):
return False
if s3[0]==s1[0]:
# 注意与return self.isInterleave(s1[1:],s2[:],s3[1:])的区别
if self.isInterleave(s1[1:],s2[:],s3[1:]):
return True
if s3[0]==s2[0]:
if self.isInterleave(s1[:],s2[1:],s3[1:]):
return True
return False
89. 格雷编码
直接记
class Solution:
def grayCode(self, n: int) -> List[int]:
# ^ 代表异或 &代表并 |代表或
return [i^(i//2) for i in range(pow(2,n))]