题86(中等):
python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:#分组,分两丢small_node=ListNode()high_node=ListNode()p_small=small_nodep_high=high_nodep_h=headwhile p_h!=None:#如果小于,应该放到smallerprint(p_h.val)if p_h.val<x:p_small.next=p_hp_small=p_small.nextp_h=p_h.nextelse:p_high.next=p_hp_high=p_high.nextp_h=p_h.nextp_small.next=high_node.nextp_high.next=Nonehead=small_node.nextreturn head
题87(困难):
python代码:
class Solution:def isScramble(self, s1: str, s2: str) -> bool:if len(s1) != len(s2) or sorted(s1) != sorted(s2):return Falsen = len(s1)dp = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)]# 初始化长度为1的子串for i in range(n):for j in range(n):dp[i][j][1] = s1[i] == s2[j]# 遍历所有可能的子串长度for k in range(2, n + 1):for i in range(n - k + 1):for j in range(n - k + 1):for p in range(1, k):# 不交换的情况if dp[i][j][p] and dp[i + p][j + p][k - p]:dp[i][j][k] = Truebreak# 交换的情况if dp[i][j + k - p][p] and dp[i + p][j][k - p]:dp[i][j][k] = Truebreakreturn dp[0][0][n]
题88(简单):
python代码:
class Solution:def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:"""Do not return anything, modify nums1 in-place instead."""for i in range(m,m+n):nums1[i]=nums2[i-m]nums1.sort()
题89(中等):
分析:
找规律00 01 11 10-----> 000 001 011 010(前4+0) / 110 111 101 100 (后4加1并倒序排列)
class Solution:def grayCode(self, n: int) -> List[int]:def call_back(n,bin_list):if n == 1:bin_list.extend(['0', '1'])return bin_listbin_list=call_back(n - 1,bin_list)new = ['1' + i for i in bin_list][::-1]bin_list=['0' + i for i in bin_list]print(new)bin_list.extend(new)return bin_listbin_list=call_back(n,[])return [int(i, 2) for i in bin_list]
题90(中等):
python代码:
class Solution:def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:n_list=sorted(nums)res=[[]]def call_back(nums,k,now_list):#判断出递归条件,当if nums==[]:returnfor i in range(0,len(nums)):if i>0 and nums[i]==nums[i-1]:continue#加一个i处的值new_now=now_list.copy()new_now.append(nums[i])#把这个去了new_num=nums[i+1:]res.append(new_now)call_back(new_num,k+1,new_now)call_back(n_list,0,[])return res