Matrix Chain Multiplication-geeksforgeeks

(ABC)D = (AB)(CD) = A(BCD) calculate the least calculation.

第一种方法穷举发,willl take np time.
 
 
def matrixp(p,i,j):
    if i==j:
        return 0
    k=i
    minval=10000000
    while k<j:
        result=matrixp(p,i,k)+matrixp(p,k+1,j)+p[i-1]*p[k]*p[j]
        if minval>result:
            minval=result
        k+=1
    return minval

def main():
    p=[40,20,10,30,10]
    print matrixp(p,1,len(p)-1)
    

if __name__=="__main__":
    main()


另外一种方法是用动态规划,bottom up solution

需要用o(n^3) 空间o(n^2)

def matrixpp(p,n):
    minval=10000000
    m=[[0 for i in range(n)] for j in range(n)]
    for i in range(n):
        m[i][i]=0
        
    for L in range(2,n):
        for i in range(1,n-L+1):
            print j
            j=i+L-1
            m[i][j]=minval
            for k in range(i,j):
                q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j]
                if q<m[i][j]:
                    m[i][j]=q
    return m[1][n-1]
    
    




你可能感兴趣的:(动态规划,Matrix,geeksforgeeks)