三角形最小路径和
动态规划:
直接在原数组中修改,避免额外空间占用
PHP,20ms
class Solution {
/**
* @param Integer[][] $triangle
* @return Integer
*/
function minimumTotal($triangle) {
if(count($triangle)==0) return 0;
if(count($triangle)==1) return min($triangle[0]);
for($i = 1;$i < count($triangle);$i++){
for($j = 0;$j < count($triangle[$i]);$j++){
if($j==0){
$triangle[$i][$j] += $triangle[$i-1][$j];
}elseif($j==count($triangle[$i])-1){
$triangle[$i][$j] += $triangle[$i-1][$j-1];
} else {
$triangle[$i][$j] += min($triangle[$i-1][$j],$triangle[$i-1][$j-1]);
}
}
}
return min($triangle[count($triangle)-1]);
}
}
golang,8ms
func minimumTotal(triangle [][]int) int {
if len(triangle) == 0 {
return 0;
}
if len(triangle) == 1 {
return min(triangle[0]...)
}
for i := 1;i < len(triangle);i++ {
for j := 0;j < len(triangle[i]);j++ {
if j == 0 {
triangle[i][j] +=triangle[i-1][j]
}else if j == len(triangle[i])-1 {
triangle[i][j] += triangle[i-1][j-1]
}else {
triangle[i][j] += min(triangle[i-1][j],triangle[i-1][j-1])
}
}
}
return min(triangle[len(triangle)-1]...)
}
func min(element... int) int{
var arr []int
arr = append(arr,element...)
minNum := arr[0]
for _,v := range arr {
if v < minNum {
minNum = v
}
}
return minNum
}