编译错误:非常量数组边界(动态规划)

huangapple go评论76阅读模式
英文:

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 &lt;= m; i++ {
        dp[i][0] = dp[i-1][0] + grid[i][0]
    }

    //for row initialization
    for j := 0; j &lt;= n; j++ {
        dp[0][j] = dp[0][j-1] + grid[0][j]
    }
    for i := 0; i &lt;= m; i++ {
        for j := 0; j &lt;= 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)
}

huangapple
  • 本文由 发表于 2017年6月15日 01:28:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/44551138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定