当前位置:网站首页>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
边栏推荐
- [SQL statement basics] - select (supplement to single table query sequence)
- Nature communications - modeling armed conflict risk under climate change using machine learning and time series data
- 面试技巧问答
- F2. nearest beautiful number (hard version)
- Interview skills Q & A
- 程序员面试这么重视考察概念还是第一次见
- VSCode 如何将已编辑好的文件中的 tab 键转换成空格键
- St table learning
- 【TcaplusDB知识库】TcaplusDB单据受理-创建业务介绍
- 音视频技术开发周刊 | 249
猜你喜欢
Folder data synchronization tool sync folders Pro
[tcapulusdb knowledge base] tcapulusdb Model Management Introduction
ue5 小知识点 random point in Bounding Boxf From Stream
[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (I)
区间修改乘和加(理解懒标记的好例题)
Tamidog knowledge | a comprehensive analysis of the meaning and role of mergers and acquisitions of state-owned enterprises
2021CCPC网络赛榜单
关于 SAP Spartacus CmsService.getComponentData 可能的优化思路
vivo大规模 Kubernetes 集群自动化运维实践
第七章 文件管理作业
随机推荐
Will it be a great opportunity for entrepreneurs for Tiktok to attach so much importance to live broadcast sales of takeout packages?
手动加密 ESP 设备量产固件并烧录的流程
Socket programming (Part 1)
Based on vue+nest Js+mysql cross platform open source community operation management system
Digital DP example
CommonAPI与AUTOSAR AP通讯管理的异同
C#/VB. Net to generate directory bookmarks when word is converted to PDF
Vivo large scale kubernetes cluster automation operation and maintenance practice
vivo大规模 Kubernetes 集群自动化运维实践
WinForm resolves frequent refresh of black screen
Interval modification multiplication and addition (a good example of understanding lazy tags)
VSCode 如何将已编辑好的文件中的 tab 键转换成空格键
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,
DNS protocol analysis
Miidock file distribution
Pagoda access changed from IP to domain name
Anonymity in Web3 and NFT
[SQL statement basics] - select (supplement to single table query sequence)
(幼升小信息-03)批量模板制作 幼儿基本信息收集文件夹(包含PDF、Word、证件文件夹)
Inclusion exclusion principle (number divisible)