当前位置:网站首页>break algorithm---dynamic planning(dp-arr)
break algorithm---dynamic planning(dp-arr)
2022-06-13 11:39:00 【Nonxinyou】
Statement :
The algorithm is based on https://labuladong.github.io/
python Language implementation
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]: The value is nums[i] At the end of the LIS value
# Find the number that ends with each number in the array LIS, The final answer is the biggest one
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)
# By width w Ascending order , If the width is the same , According to the height h Descending order : Put the sorted h As an array , Calculate on this array LIS The length of is the final answer .
envelopes.sort(key=lambda x: (x[0], -x[1]))
# Look for the height array 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]: The value is nums[i] At the end of the LIS value
# Find the number that ends with each number in the array LIS, The final answer is the biggest one
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] The meaning is : about s1[1..i] and s2[1..j], Their LCS The length is dp[i][j].
''' NOTE: about m That's ok n Two dimensional array of columns java 2D array initialization :int[][] dp = new int[m + 1][n + 1]; <= Before and after python 2D array initialization :dp = [[0 for col in range(n+1)] for row in range(m+1)] <= Go before you go '''
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m = len(text1)
n = len(text2)
# Definition :text1[0..i-1] and text2[0..j-1] Of lcs The length is dp[i][j]
dp = [[0 for col in range(n+1)] for row in range(m+1)]
# The goal is :text1[0..m-1] and text2[0..n-1] Of lcs length , namely 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):
# Now? i and j from 1 Start , Therefore, it is necessary to reduce 1
if text1[i - 1] == text2[j - 1]:
# text1[i-1] and text2[j-1] equal , Then the character must be in lcs in
dp[i][j] = dp[i - 1][j - 1] + 1
else:
# text1[i-1] and text2[j-1] It's not equal , Then one of these two characters must be absent lcs in
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
边栏推荐
- Auto.js 悬浮窗居中
- 【TcaplusDB知识库】Tmonitor后台一键安装介绍(一)
- [tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (I)
- Euler function and finding Euler function by linear sieve
- (Yousheng small message-04) how to use mobile WPS for electronic signature on PDF
- 1051. height checker
- MFC custom button to realize color control
- What is the appropriate setting for the number of database connections?
- We spent a weekend migrating 3.7 million lines of code to typescript
- Model building process 1==miidock
猜你喜欢
Camunda定时器事件示例Demo(Timer Events)
Lvgl Library Tutorial 01- porting to STM32 (touch screen)
17 pictures: read and understand the first domestic guide for mainframe security capacity building
Performance monster on arm64: installation and performance test of API gateway Apache APIs IX on AWS graviton3
【TcaplusDB知识库】Tmonitor后台一键安装介绍(二)
[tcapulusdb knowledge base] tcapulusdb doc acceptance - create business introduction
Ue5 small knowledge points geometry script modeling
[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (I)
【TcaplusDB知识库】TcaplusDB机型管理介绍
领导说要明天上线,这货压根不知道开发流程
随机推荐
【TcaplusDB知识库】Tmonitor单机安装指引介绍(一)
Adaptation of multi system docking and application of packaging mode
元宇宙土地:是什么让数字房地产变得有价值
How to open an account for your own stock trading? Is it safe and reliable?
欧拉函数和线性筛求欧拉函数
Meta universe land: what makes digital real estate valuable
Nim游戏阶梯 Nim游戏和SG函数应用(集合游戏)
ARM64 上的性能怪兽:API 网关 Apache APISIX 在 AWS Graviton3 上的安装和性能测试
[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (II)
1051. 高度检查器
2021CCPC网络赛题解加总结
【TcaplusDB知识库】TcaplusDB新增机型介绍
Socket programming (Part 1)
[tcapulusdb knowledge base] tcapulusdb doc acceptance - table creation approval introduction
CommonAPI与AUTOSAR AP通讯管理的异同
[tcapulusdb knowledge base] tcapulusdb operation and maintenance doc introduction
How fastapi responds to file downloads
Ue5 small knowledge points geometry script modeling
It's the first time that the programmer interview pays so much attention to the concept of investigation
Interview skills Q & A