【发布时间】:2018-10-11 16:42:21
【问题描述】:
我得到了错误:表达式必须在第 4 行有一个常量值(int cost[n][n]),并且基于它的进一步错误,即“数组类型 int[n][n] 不可赋值” 。 我该如何解决?
int optimalSearchTree(int keys[], int freq[], int n)
{
/* Create an auxiliary 2D matrix to store results of subproblems */
int cost[n][n];
for (int i = 0; i < n; i++)
cost[i][i] = freq[i];
for (int L = 2; L <= n; L++)
{
// i is row number in cost[][]
for (int i = 0; i <= n - L + 1; i++)
{
// Get column number j from row number i and chain length L
int j = i + L - 1;
cost[i][j] = INT_MAX;
// Try making all keys in interval keys[i..j] as root
for (int r = i; r <= j; r++)
{
// c = cost when keys[r] becomes root of this subtree
int c = ((r > i) ? cost[i][r - 1] : 0) +
((r < j) ? cost[r + 1][j] : 0) +
sum(freq, i, j);
if (c < cost[i][j])
cost[i][j] = c;
}
}
}
return cost[0][n - 1];
}
【问题讨论】:
-
使用合适的容器,例如:
std::vector -
int cost[n][n];不是有效的 C++。 -
喜欢 std::vector int cost[n][n]?
-
@NeilButterworth 对于一个 1 级的人来说,n*n 向量的语法是什么并不明显(我必须查一下)让我们有点好意
标签: c++