Leetcode_120

题目描述

给定一个三角形,找出从顶到底的最小路径和,每一步可以从上一行移动到下一行相邻的数字

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

解题思路

递推方程: 
  f(0,0)=a[0][0] 
  f(i,0)=a[i][0]+f(i-1,0) (i>0) 
  f(i,i)=a[i][i]+f(i-1,i-1)(i>0) 
  f(i,j)=a[i][j]+MIN(f(i-1,j),f(i-1,j-1))

python

import copy
class Solution:
    def minimumTotal(self, triangle):
        """
        :type triangle: List[List[int]]
        :rtype: int
        """
        temp = copy.deepcopy(triangle)

        for i in range(1,len(temp)):
            for j in range(len(temp[i])):
                if j==0:
                    temp[i][j] = triangle[i][j]+temp[i-1][j]
                elif j1][j],temp[i-1][j-1])
                elif j==i:
                    temp[i][j] = triangle[i][j]+temp[i-1][j-1]

        return min(temp[-1])


if __name__ == '__main__':
    a = Solution()
    test = [[1],[2,3],[3,4,5]]
    print(a.minimumTotal(test))

应该不是最优雅的写法,算是勉强实现了想法吧。

import java.util.List;

public class Solution {

    public int minimumTotal(List> triangle) {

        if (triangle == null || triangle.size() < 1) {
            return 0;
        }
        // 创建数组的第二维度
        int[][] minSum = new int[triangle.size()][];

        // 创建数组的第一维度
        for (int i = 0; i < minSum.length; i++) {
            minSum[i] = new int[i + 1];
        }
        // 设置第一行
        minSum[0][0] = triangle.get(0).get(0);
        // 设置其它行
        for (int i = 1; i < minSum.length; i++) {
            List line = triangle.get(i);
            for (int j = 0; j < minSum[i].length; j++) {
                if (j == 0) {
                    minSum[i][0] = line.get(0) + minSum[i - 1][0];
                } else if (i == j) {
                    minSum[i][j] = line.get(j) + minSum[i - 1][j - 1];
                } else if (j < i) {
                    minSum[i][j] = line.get(j) + Math.min(minSum[i - 1][j], minSum[i - 1][j - 1]);
                }
            }
        }
        //找最后一行的最小值就是所求的解
        int min = minSum[minSum.length - 1][0];
        int length = minSum[minSum.length - 1].length;
        for (int i = 1; i < length; i++) {
            if (min > minSum[length - 1][i]) {
                min = minSum[length - 1][i];
            }
        }

        return min;
    }
}

你可能感兴趣的:(编码)