classSolution:deflongestPalindromeSubseq(self, s:str)->int:n=len(s)dp=[[0]*n for _ inrange(n)]for i inrange(n):dp[i][i]=1for i inrange(n,-1,-1):for j inrange(i+1,n):if s[i]==s[j]:dp[i][j]=dp[i+1][j-1]+2else:dp[i][j]=max(dp[i][j-1],dp[i+1][j])return dp[0][-1]
leetcode 72:编辑距离
classSolution:defminDistance(self, word1:str, word2:str)->int:a=len(word1)b=len(word2)dp=[[0for _ inrange(b+1)]for _ inrange(a+1)]for i inrange(b+1):dp[0][i]=ifor j inrange(a+1):dp[j][0]=jfor i inrange(1,a+1):for j inrange(1,b+1):if word1[i-1]==word2[j-1]:dp[i][j]=dp[i-1][j-1]else:dp[i][j]=min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1return dp[-1][-1]
leetcode 198:打家劫舍
classSolution:defrob(self, nums: List[int])->int:if(not nums):return0iflen(nums)==1:return nums[0]a=len(nums)dp=[0]*adp[0]=nums[0]dp[1]=max(nums[0],nums[1])for i inrange(2,a):dp[i]=max(dp[i-2]+nums[i],dp[i-1])return dp[-1]
leetcode 213:打家劫舍II
classSolution:defrob(self, nums: List[int])->int:if(not nums):return0eliflen(nums)<=2:returnmax(nums)defhelper(nums):iflen(nums)<=2:returnmax(nums)dp=[0]*len(nums)dp[0]=nums[0]dp[1]=max(nums[0],nums[1])for i inrange(2,len(nums)):dp[i]=max(dp[i-1],dp[i-2]+nums[i])return dp[-1]returnmax(helper(nums[1:]),helper(nums[:-1]))