当前位置:网站首页>break algorithm---dynamic planning(dp-arr)
break algorithm---dynamic planning(dp-arr)
2022-06-13 11:21:00 【壬辛酉】
声明:
算法基于https://labuladong.github.io/
python语言实现
300.longest-increasing-subsequence
354. Russian Doll Envelopes
1143. Longest Common Subsequence
1425. Constrained Subsequence Sum
300.longest-increasing-subsequence
from typing import List
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
# dp[i]:其值为以nums[i]结尾的LIS值
# 求出数组中以每个数字结尾的LIS,最终答案为其中最大的
dp = [1] * len(nums)
for i in range(0, len(nums), 1):
for j in range(0, i, 1):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
res = 0
for i in range(len(nums)):
res = max(res, dp[i])
return res
def main():
# Input: nums = [10,9,2,5,3,7,101,18]
# Output: 4
# Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
solution1 = Solution()
print(solution1.lengthOfLIS(nums=[10, 9, 2, 5, 3, 7, 101, 18]))
# Input: nums = [0,1,0,3,2,3]
# Output: 4
solution2 = Solution()
print(solution2.lengthOfLIS(nums=[0, 1, 0, 3, 2, 3]))
# Input: nums = [7,7,7,7,7,7,7]
# Output: 1
solution3 = Solution()
print(solution3.lengthOfLIS(nums=[7, 7, 7, 7, 7, 7, 7]))
if __name__ == '__main__':
main()
354. Russian Doll Envelopes
from typing import List
from bisect import *
class SolutionTimeLimitExceeded:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
w = len(envelopes)
# 按宽度w升序排列,若宽度一样,则按高度h降序排列:把排序后的h作为一个数组,在这个数组上计算LIS的长度就是最终答案。
envelopes.sort(key=lambda x: (x[0], -x[1]))
# 对高度数组寻找LIS
height = [0] * w
for i in range(w):
height[i] = envelopes[i][1]
return self.lengthOfLIS(height)
def lengthOfLIS(self, nums: List[int]) -> int:
# dp[i]:其值为以nums[i]结尾的LIS值
# 求出数组中以每个数字结尾的LIS,最终答案为其中最大的
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(0, i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
res = 1
for i in range(len(nums)):
res = max(res, dp[i])
return res
class Solution:
def maxEnvelopes(self, E: List[List[int]]) -> int:
E.sort(key=lambda x: (x[0], -x[1]))
dp = []
for _, height in E:
left = bisect_left(dp, height)
if left == len(dp):
dp.append(height)
else:
dp[left] = height
return len(dp)
def main():
# Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
# Output: 3
# Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
solution1 = Solution()
print(solution1.maxEnvelopes([[5, 4], [6, 4], [6, 7], [2, 3]]))
# Input: envelopes = [[1,1],[1,1],[1,1]]
# Output: 1
solution2 = Solution()
print(solution2.maxEnvelopes([[1, 1], [1, 1], [1, 1]]))
# Input: [[1,15],[7,18],[7,6],[7,100],[2,200],[17,30],[17,45],[3,5],[7,8],[3,6],[3,10],[7,20],[17,3],[17,45]]
# Output: 6
# Expected: 3
solution3 = Solution()
print(solution3.maxEnvelopes(
[[1, 15], [7, 18], [7, 6], [7, 100], [2, 200], [17, 30], [17, 45], [3, 5], [7, 8], [3, 6], [3, 10], [7, 20],
[17, 3], [17, 45]]))
if __name__ == '__main__':
main()
1143. Longest Common Subsequence
# dp[i][j] 的含义是:对于 s1[1..i] 和 s2[1..j],它们的 LCS 长度是 dp[i][j]。
''' NOTE: 对于m行n列的二维数组 java二维数组初始化:int[][] dp = new int[m + 1][n + 1]; <=前行后列 python二维数组初始化:dp = [[0 for col in range(n+1)] for row in range(m+1)] <=前列后行 '''
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m = len(text1)
n = len(text2)
# 定义:text1[0..i-1]和text2[0..j-1]的lcs长度为dp[i][j]
dp = [[0 for col in range(n+1)] for row in range(m+1)]
# 目标:text1[0..m-1]和text2[0..n-1]的lcs长度,即dp[m][n]
# base case: dp[0][..]=dp[..][0]=0
for i in range(1, m + 1, 1):
for j in range(1, n + 1, 1):
# 现在i和j从1开始,故需减1
if text1[i - 1] == text2[j - 1]:
# text1[i-1]和text2[j-1]相等,则该字符必在lcs中
dp[i][j] = dp[i - 1][j - 1] + 1
else:
# text1[i-1]和text2[j-1]不相等,则这两个字符必有一个不在lcs中
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])
return dp[m][n]
def main():
# Input: text1 = "abcde", text2 = "ace"
# Output: 3
# Explanation: The longest common subsequence is "ace" and its length is 3.
solution1 = Solution()
print(solution1.longestCommonSubsequence(text1="abcde", text2="ace"))
# Input: text1 = "abc", text2 = "abc"
# Output: 3
# Explanation: The longest common subsequence is "abc" and its length is 3.
solution2 = Solution()
print(solution2.longestCommonSubsequence(text1="abc", text2="abc"))
# Input: text1 = "abc", text2 = "def"
# Output: 0
# Explanation: There is no such common subsequence, so the result is 0.
solution3 = Solution()
print(solution3.longestCommonSubsequence(text1="abc", text2="def"))
if __name__ == '__main__':
main()
1425. Constrained Subsequence Sum
边栏推荐
- 【TcaplusDB知识库】Tmonitor系统升级介绍
- [tcapulusdb knowledge base] Introduction to tcapulusdb general documents
- 第七章 文件管理作业
- Nature communications - modeling armed conflict risk under climate change using machine learning and time series data
- ACP | 东北地理所在气象-空气质量双向耦合模式研究中取得进展
- vivo大规模 Kubernetes 集群自动化运维实践
- CommonAPI与AUTOSAR AP通讯管理的异同
- Chapter VII document management
- Alibaba's employees decreased by 4000 in the first quarter; Programmers wrote scripts to hang up vaccine numbers and were arrested for making a profit of 400000 yuan; Sohu encounters epic email fraud,
- 欧拉函数和线性筛求欧拉函数
猜你喜欢

ue5 小知识点 random point in Bounding Boxf From Stream

元宇宙土地:是什么让数字房地产变得有价值

我是如何解决码云图床失效问题?

数位DP例题

【TcaplusDB知识库】Tmonitor单机安装指引介绍(一)

The leader said he would go online tomorrow, but he didn't know the development process at all

St table learning

Euler function and finding Euler function by linear sieve

第七章 文件管理作业
![[tcapulusdb knowledge base] tcapulusdb cluster management introduction](/img/c1/62276c344ded6c260070f0d60bce81.png)
[tcapulusdb knowledge base] tcapulusdb cluster management introduction
随机推荐
Performance monster on arm64: installation and performance test of API gateway Apache APIs IX on AWS graviton3
Vivo large scale kubernetes cluster automation operation and maintenance practice
17张图:读懂国内首个《主机安全能力建设指南》
2021CCPC网络赛榜单
socket编程(上)
About SAP Spartacus cmsservice Possible optimization ideas for getcomponentdata
高斯消元求n元方程组
【TcaplusDB知识库】Tmonitor后台一键安装介绍(二)
[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (I)
Prim finding minimum spanning tree (naive dense graph)
F2. nearest beautiful number (hard version)
Chapter VII document management
Determine the maximum match between bipartite graph and bipartite graph
[tcapulusdb knowledge base] Introduction to tcapulusdb general documents
手动加密 ESP 设备量产固件并烧录的流程
Web 3.0?高成本版的P2P而已
fastapi 如何响应文件下载
我是如何解决码云图床失效问题?
Based on vue+nest Js+mysql cross platform open source community operation management system
欧拉函数和线性筛求欧拉函数