程序员代码面试指南

1、换钱的方法数

链接:1、https://blog.csdn.net/qq_34342154/article/details/77122125

2、https://www.nowcoder.com/practice/39cb6c6e2b844a8cba382c8e26951e0atpId=101&tqId=33087&tPage=1&rp=1&ru=/ta/programmer-code-interview-guide&qru=/ta/programmer-code-interview-guide/question-ranking

import sys
line1=sys.stdin.readline().strip()
values1=list(map(int,line1.split()))
line2=sys.stdin.readline().strip()
values2=list(map(int,line2.split()))
lie=values1[0]
 
target=values1[1]

def coins5(arr, aim):
    if arr == None or len(arr) == 0 or aim < 0:
        return 0
    dp = [0 for i in range(aim+1)]
    for i in range(aim//arr[0]+1):
        dp[arr[0]*i] = 1
#    for i in range(1,len(arr)):
#        for j in range(1, aim+1):
#            dp[j] += dp[j-arr[i]] if j-arr[i] >= 0 else 0
    for i in range(1,len(arr)):##比上面一步有优化了一点,在for循环的位置上
        for j in range(arr[i], aim+1):
            dp[j] += dp[j-arr[i]]
    return dp[aim]%(1000000007)

print(coins5(values2 ,target))

2、最长公共子序列

1、https://www.cnblogs.com/CheeseZH/p/8830482.html

2、https://blog.csdn.net/hrn1216/article/details/51534607

地址是:C:\Users\xuhaohao\Desktop\bishi_code\byme\最长公共子串与最长公共子序列

def bottom_up_dp_lcs(str_a, str_b):
    if len(str_a)==0 or len(str_b)==0:
        return 0
    len_a=len(str_a)
    len_b=len(str_b)
    dp=[[0 for _ in range(len_b+1)] for _ in range(len_a+1)]
    
    for i in range(1,len_a+1):
        for j in range(1,len_b+1):
            
            if str_a[i-1]==str_b[j-1]:
                dp[i][j]=dp[i-1][j-1]+1
            else:
                dp[i][j]=max(dp[i-1][j],dp[i][j-1])
    
    print("lenfth of lcs is ",dp[len_a][len_b])
    lcs=""
    while len_a >0 and len_b>0:
        if str_a[len_a-1]==str_b[len_b-1] and dp[len_a][len_b]==dp[len_a-1][len_b-1]+1:
            lcs=str_a[len_a-1]+lcs
            len_a,len_b=len_a-1,len_b-1
            continue
        
        if dp[len_a][len_b]==dp[len_a][len_b-1]:
            len_a,len_b=len_a,len_b-1
            continue
        if dp[len_a][len_b]==dp[len_a-1][len_b]:
            len_a,len_b=len_a-1,len_b
            continue
    print("lcs is ",lcs)

#最长公共子序列的二维DP的写法
def bottom_up_dp_lcs1(str_a,str_b):
    if len(str_a)==0 and len(str_b)==0:
        return 0
    len_a=len(str_a)
    len_b=len(str_b)
    
    dp=[[0 for _ in range(len_b+1)] for _ in range(len_a+1)]
    
    max_len=0
    lcs_str=''
    for i in range(1,len_a+1):
        
        for j in range(1,len_b+1):
            
             if str_a[i-1]==str_b[j-1]:
                dp[i][j]=dp[i-1][j-1]+1
                
                max_len = max([max_len, dp[i][j]])
                if max_len == dp[i][j]:
                    lcs_str = str_a[i-max_len:i]     
             else:
                dp[i][j]=0
    print("length of lcs is :", max_len)
    print("lcs:", lcs_str)
最长公共子串的二维dp的写法

 

你可能感兴趣的:(程序员代码面试指南,程序员代码面试指南)