英文:
Compile Error : Non-Constant Array Bound (Dynamic Programming)
问题
你好!以下是你提供的代码的翻译:
func minPathSum(grid [][]int) int {
var dp [m+1][n+1]int
dp[0][0] = grid[0][0]
// 初始化列
for i := 0; i <= m; i++ {
dp[i][0] = dp[i-1][0] + grid[i][0]
}
// 初始化行
for j := 0; j <= n; j++ {
dp[0][j] = dp[0][j-1] + grid[0][j]
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + grid[i][j]
}
}
return dp[m][n]
}
请注意,这只是代码的翻译,我无法提供有关编译错误的帮助。如果你有编译错误,请提供错误信息,我将尽力帮助你解决问题。
英文:
Im trying to solve the minimum path sum problem of Dynamic programming using golang and below is my program for that which shows compilation error.
enter code here
func minPathSum(grid [][]int) int {
var dp[m+1][n+1] int
dp[0][0] = grid[0][0]
//for column initialization
for i := 0; i <= m; i++ {
dp[i][0] = dp[i-1][0] + grid[i][0]
}
//for row initialization
for j := 0; j <= n; j++ {
dp[0][j] = dp[0][j-1] + grid[0][j]
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + grid[i][j]
}
}
return dp[m][n]
}
答案1
得分: 4
如@Motakjuq在评论中提到的:你不能定义一个动态数组,数组的两个维度都必须是常量,但是切片可以帮助你。
可以使用以下代码:
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
}
英文:
As @Motakjuq mentioned in comment: you cannot define a dynamic array, both dimensions must be constant for an array, but slice will help you.
Use something like this:
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论