剑指 Offer II 099. 最小路径之和
2022-07-13 本文已影响0人
邦_
func minPathSum(_ grid: [[Int]]) -> Int {
let row = grid.count
let col = grid.first?.count ?? 0
let temp = Array.init(repeating: 0, count: col)
var dp = Array.init(repeating: temp, count: row)
for i in 0..<row{
for j in 0..<col {
if i == 0 && j == 0{
dp[0][0] = grid[0][0]
}else if i == 0 {
dp[0][j] += dp[0][j - 1] + grid[i][j]
}else if j == 0 {
dp[i][0] = dp[i - 1][0] + grid[i][j]
}else {
dp[i][j] = min(dp[i - 1][j] , dp[i][j - 1]) + grid[i][j]
}
}
}
return dp[row - 1][col - 1]
}