动态规划(五)——双序列型动态规划

动态规划经典题目解析

这里写图片描述

Longest Common Subsequence

这里写图片描述
这里写图片描述

class Solution:
    """
    @param A: A string
    @param B: A string
    @return: The length of longest common subsequence of A and B
    """
    def longestCommonSubsequence(self, A, B):
        # write your code here
        if not A or not B:
            return 0

        len1=len(A)
        len2=len(B)

        f=[[0]*(len2+1) for _ in range(len1+1)]



        for i in range(1,len1+1):
            for j in range(1,len2+1):
                if A[i-1]==B[j-1]:
                    f[i][j]=f[i-1][j-1]+1
                else:
                    f[i][j]=max(f[i-1][j],f[i][j-1])

        return f[-1][-1]

Interleaving String

这里写图片描述

class Solution:
    """
    @param s1: A string
    @param s2: A string
    @param s3: A string
    @return: Determine whether s3 is formed by interleaving of s1 and s2
    """
    def isInterleave(self, s1, s2, s3):
        # write your code here
        if not s1:
            return s3==s2

        if not s2:
            return s3==s1

        if len(s1)+len(s2)!=len(s3):
            return False

        len1=len(s1)
        len2=len(s2)
        f=[[False]*(len2+1) for i in range(len1+1)]
        f[0][0]=True

        for i in range(0,len1+1):
            for j in range(0,len2+1):
                k=i+j
                if i>=1 and s3[k-1]==s1[i-1]:
                    f[i][j]=f[i-1][j]
                if j>=1 and s3[k-1]==s2[j-1]:
                    f[i][j]=f[i][j] or f[i][j-1]

        return f[-1][-1]

Edit distance

这里写图片描述
这里写图片描述

class Solution:
    """
    @param word1: A string
    @param word2: A string
    @return: The minimum number of steps.
    """
    def minDistance(self, word1, word2):
        # write your code here
        if not word1 and not word2:
            return 0
        if not word1:
            return len(word2)
        if not word2:
            return len(word1)

        len1=len(word1)
        len2=len(word2)

        f=[[float('inf')]*(len2+1) for i in range(len1+1)]

        f[0][0]=0

        for i in range(len1+1):
            for j in range(len2+1):
                if i==0:
                    f[i][j]=j
                if j==0:
                    f[i][j]=i

                if i>=1 and j>=1:
                    if word1[i-1]==word2[j-1]:
                        f[i][j]=f[i-1][j-1]
                    else:
                        f[i][j]=min(f[i][j-1]+1,f[i-1][j]+1,f[i-1][j-1]+1)

        return f[-1][-1]

Distinct Subsequence

这里写图片描述
这里写图片描述

class Solution:
    """
    @param: : A string
    @param: : A string
    @return: Count the number of distinct subsequences
    """

    def numDistinct(self, S, T):
        # write your code here
        if not S:
            return 0
        if not T:
            return 1

        n1=len(S)
        n2=len(T)

        f=[[0]*(n2+1) for i in range(n1+1)]
        for i in range(n1+1):
            for j in range(n2+1):
                if j==0:
                    f[i][j]=1
                    continue

                if i==0:
                    f[i][j]=0
                    continue
                f[i][j]=f[i-1][j]
                if S[i-1]==T[j-1]:
                    f[i][j]=f[i][j]+f[i-1][j-1]


        return f[-1][-1]

Regular Expression Matching

这里写图片描述
这里写图片描述
这里写图片描述

class Solution:
    """
    @param s: A string 
    @param p: A string includes "." and "*"
    @return: A boolean
    """
    def isMatch(self, s, p):
        # write your code here

        n1=len(s)
        n2=len(p)

        match=[[False]*(n2+1) for i in range(n1+1)]

        for i in range(n1+1):
            for j in range(n2+1):
                if i==0 and j==0:
                    match[i][j]=True
                    continue

                if j==0 and i>=1:
                    match[i][j]=False
                    continue

                if p[j-1]!="*":
                    if i>=1 and (p[j-1]=="." or s[i-1]==p[j-1]):
                        match[i][j]=match[i-1][j-1]
                else:#p[j-1]=="*"
                    if j>=2:
                        match[i][j]=match[i][j] or match[i][j-2]
                    if i>=1 and j>=2 and (p[j-2]=="."  or s[i-1]==p[j-2]):
                        match[i][j]=match[i][j] or match[i-1][j]


        return match[-1][-1]

Wildcard matching

这里写图片描述

class Solution:
    """
    @param s: A string 
    @param p: A string includes "?" and "*"
    @return: is Match?
    """
    def isMatch(self, s, p):
        # write your code here

        n1=len(s)
        n2=len(p)
        match=[[False]*(n2+1) for i in range(n1+1)] 

        for i in range(n1+1):
            for j in range(n2+1):
                if i==0 and j==0:
                    match[i][j]=True
                    continue

                if j==0 and i>=1:
                    match[i][j]=False
                    continue

                if p[j-1]!="*":
                    if i>=1 and (p[j-1]=='?' or p[j-1]==s[i-1]):
                        match[i][j]=match[i-1][j-1]
                else: # p[j-1]=="*"
                    match[i][j]=match[i][j-1]# 匹配空字符串
                    if i>=1:
                        match[i][j]=match[i][j] or match[i-1][j] # *匹配至少一个字符

        return match[-1][-1]

总结:
这里写图片描述

ones and zeros

这里写图片描述
这里写图片描述
这里写图片描述

class Solution:
    """
    @param strs: an array with strings include only 0 and 1
    @param m: An integer
    @param n: An integer
    @return: find the maximum number of strings
    """
    def findMaxForm(self, strs, m, n):
        # write your code here

        numStr=len(strs)

        count=[[0]*2 for i in range(numStr)]
        for i,s in enumerate(strs):
            for letter in s:
                if letter=="0":
                    count[i][0]=count[i][0]+1
                else:
                    count[i][1]=count[i][1]+1

        f=[[[0]*(n+1) for i in range(m+1)] for _ in range(numStr+1)]

        for i in range(numStr+1):
            for j in range(m+1):
                for k in range(n+1):
                    if i==0:
                        f[i][j][k]=0
                        continue

                    f[i][j][k]=f[i-1][j][k] # strs[i-1] not selected
                    if count[i-1][0]<=j and count[i-1][1]<=k:
                        f[i][j][k]=max(f[i][j][k],f[i-1][j-count[i-1][0]][k-count[i-1][1]]+1) #不要忘记加1

        return f[-1][m][n]
### 维持阻塞D触发器的功能测试 #### 测试环境搭建 为了对维持阻塞D触发器进行功能测试,需准备必要的设备和材料。这通常包括但不限于信号发生器、逻辑分析仪或示波器、电源供应器以及用于连接的面包板和跳线。对于具体的器件选择,74LS74作为一款常见的D触发器IC,非常适合此类实验[^3]。 #### 功能测试方法 在执行具体测试之前,应先理解维持阻塞D触发器的工作原理。这种类的触发器通过引入额外的延迟机制来防止数据竞争冒险现象的发生,在时钟脉冲上升沿到来前锁定输入端的数据变化,从而确保输出稳定可靠[^2]。 - **静态特性验证** 设置不同的初始条件(如设置`D=0`或`D=1`),观察并记录当时钟信号处于低电平(`CLK=0`)状态下Q端的状态。此时无论D输入如何改变,只要时钟未激活,则输出不应发生变化。 - **动态响应测量** 当给定一个正向边沿触发事件(即将时钟由低变高)的同时施加特定模式下的D输入序列,利用逻辑分析工具捕捉整个过程中各节点电压的变化情况。重点在于确认每当有新的有效时钟前沿到达时,输出确实跟随当前时刻的D值更新;而在其他时间里保持不变。 - **抗干扰能力评估** 尝试人为制造一些短暂而轻微的噪声扰动作用于输入线上,检验该设计能否有效地屏蔽这些异常波动的影响而不至于引起误操作。此部分可借助专用仪器模拟实际应用场景中的电磁兼容性挑战。 ```python import numpy as np from matplotlib import pyplot as plt def simulate_d_latch(d_input, clk_signal): q_output = [] prev_clk_state = False for d, clk in zip(d_input, clk_signal): if not prev_clk_state and clk: # Detect rising edge of clock signal q_output.append(d) else: if len(q_output) > 0: q_output.append(q_output[-1]) else: q_output.append(0) prev_clk_state = clk return np.array(q_output) d_inputs = [0, 1, 1, 0, 1] clk_signals = [False, True, False, True, False] q_outputs = simulate_d_latch(d_inputs, clk_signals) plt.step(range(len(clk_signals)), q_outputs, where='post', label="Output Q") plt.plot(range(len(clk_signals)), d_inputs, 'o-', drawstyle='steps-post', label="Input D", alpha=.5) plt.xlabel('Time Step') plt.ylabel('Signal Level') plt.legend() plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值