据我所知,自下而上的复杂性应该是n ^ 3,然而,我的表明它几乎就像O(n)。我已经多次检查这些代码,但仍然不知道为什么它不是n ^ 3的复杂性。我在这里想念一下吗?
/**
* Using the bottom-up approach to fill in the table m and s for matrices P
* @param P an array storing the matrices chain
*/
public void matrixChainOrder(int[] P){
int n = P.length-1;
m = new int[n+1][n+1];
s = new int[n][n+1];
for (int i=1; i <= n; i++ ){
m[i][i] = 0;
}
for (int l = 2; l <= n; l++){
for (int i = 1; i <= n-l + 1; i++){
int j = i + l - 1;
m[i][j] = Integer.MAX_VALUE;
for (int k = i; k <= j -1; k++){
int q = m[i][k] + m[k+1][j] + P[i-1]*P[k]*P[j];
if (q < m[i][j]){
m[i][j] = q;
s[i][j] = k;
}
}
}
}
}
/**
* Print out the optimal parenthesization of matrices chain P
* @param s the auxiliary table storing the parenthesization
* @param i the index of the start matrix
* @param j the index of the end matrix
*/
public void printOptimalParens(int[][] s, int i, int j){
if (i == j){
System.out.print("A"+ i);
}
else{
System.out.print("(");
printOptimalParens(s, i, s[i][j]);
printOptimalParens(s, s[i][j] + 1, j);
System.out.print(")");
}
}
/**
* Compute the product of the matrices chain
* @param A The matrices chain, it is an array of matrices
* @param s the auxiliary table storing the parenthesization
* @param i the start matrix
* @param j the end matrix
* @return the product matrix of the matrices chain
*/
public long[][] matrixChainMultiply(long[][][] A, int[][] s, int i, int j){
if (i == j){
return A[i];
}
if (i + 1 == j){
return multiply(A[i], A[j]);
}
long[][] C = matrixChainMultiply(A, s, i, s[i+1][j+1]-1);
long[][] D = matrixChainMultiply(A, s, s[i+1][j+1], j);
return multiply(C, D);
}
/**
* A helper method to compute 2 matrices
* @param X the first matrix
* @param Y the secodn matrix
* @return the product of these two matrices
*/
public long[][] multiply(long[][] X, long[][] Y){
int r = X.length;
int c = X[0].length;
int c2 = Y[0].length;
long[][] B = new long[r][c2];
for (int u = 0; u < r; u++){
for (int v = 0; v < c2; v++){
for (int w = 0; w < c; w++){
B[u][v] += X[u][w] * Y[w][v];
}
}
}
return B;
}
答案 0 :(得分:0)
我可以告诉你,肯定不是O(N)。
第一个周期做一次,所以它是O(N-2)。 (你从数字2开始) 第二个是O(N-L-1)。 第三个是O(J-1)。
最后它是O(N *(N-L-1)*(J-1))。 简化我可以称之为O(N ^ 3)。
如果我错了,请纠正我。
自下而上是一种动态编程,它没有算法。 它可以运行在O(N)或更低,或更多,这取决于问题。