所以我正在练习解决DP问题并发现这个问题我无法理解为什么。如果我初始化大小为n的向量向量,则操作不会起作用。同时,如果我只是将成本声明为int cost [n] [n],那么确实如此。请告诉我原因。
int sum (vector<int> freq, int i, int j){
int s=0;
for (int x=i; x<=j; x++) {
s+=freq[x];
}
return s;
}
int optimalSearchTree(vector<int> keys, vector<int> freq){
int n = keys.size();
vector<vector<int>> cost( n,vector<int>( n,0 )) ;
for (int i = 0; i < n; i++) {
cost[i][i] = keys[i];
}
for (int L=2; L<=n; L++) {
for (int i = 0; i<= n-L+1; i++) {
int j = i+L-1;
cost[i][j] = INT_MAX;
for (int r=i; r<=j; r++) {
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];
}
int main(){
vector<int> keys = {10,12,16,21};
vector<int> freq = {4,2,6,3};
cout<<optimalSearchTree(keys, freq)<<endl;
// int n = keys.size();
//vector<vector<int>> cost( n,vector<int>( n,0 )) ;
//cout<<cost.size()<<" "<<cost[0].size()<<endl;
}
答案 0 :(得分:0)
我认为解决方案与此问题的解决方案相同:
Accessing an array out of bounds gives no error, why?
在其中,指定int arr [n] [n]的超出访问权限不会返回任何错误。同时从矢量访问越界位置。