Dart: 解决“Cannot add to a fixed_length list”错误
在 Dart 中,当尝试向固定长度列表添加元素时,就会出现“Cannot add to a fixed_length list”错误。这是因为固定长度列表在创建后无法修改。
例如,以下代码演示了该错误:
class Solution {
int minCostClimbingStairs(List<int> cost){
List<int> dp=List<int>.filled(2,0);
for(int i=2;i<cost.length;i++) dp.add(min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]));
return dp[dp.length-1];
}
}//第4行执行出错,Dart:Cannot add to a fixed_length list
错误出现在 dp.add() 这一行,因为 dp 是一个固定长度列表,无法添加新元素。
要解决这个问题,需要将 dp 的声明改为可增长列表,可以使用 List() 构造函数来实现。
以下是修改后的代码:
class Solution {
int minCostClimbingStairs(List<int> cost){
List<int> dp = List<int>.from([0, 0]);
for(int i=2; i<cost.length; i++) {
dp.add(min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]));
}
return dp[dp.length-1];
}
}
在这个修改后的代码中,dp 被声明为一个可增长列表,因此可以向其中添加元素。
通过使用可增长列表,我们解决了“Cannot add to a fixed_length list”错误,并确保代码能够正常运行。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qgu4 著作权归作者所有。请勿转载和采集!