leetcode-120-Triangle-等腰三角形

题目:

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

示例:

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

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

题目解析:

1.此题是等腰三角形,上下之间的关系简化为上下相邻的三个数,index相邻,大小关系是在下方二选一+上方的数值,必然正确。 根据此思路,可以top-bottom,或者bottom-top,由于可以简化,所以动态规划方法。   
2. 采用bottom-top方法,最后简化为1个值,所以左侧值放置两值中的小值。

代码:


普通代码,较慢:
class Solution_:
    def minimumTotal(self, triangle):
        """
        :type triangle: List[List[int]]
        :rtype: int
        """
        all_paths=[]
        cur_path=[triangle[0][0]]
        # cur_path=[]
        cur_index=[0,0]
        self.bfs(all_paths,cur_path,cur_index,triangle)
        print(all_paths)
        sums=[sum(elem) for elem in all_paths]
        return min(sums)
    def bfs(self,all_paths,cur_path,cur_index,triangle):
        x_cur=cur_index[0]
        # cur_row=triangle[x_cur]
        x_threshold=len(triangle)
        y_cur=cur_index[1]
        x_next=x_cur+1
        y_next=[]
        if x_next<x_threshold:
            next_row = triangle[x_cur + 1]
            y_threshold = len(next_row)
            # y_next.append(y_cur)
            # if y_cur-1>=0:
            y_next.append(y_cur)
            if y_cur+1<y_threshold:
                y_next.append(y_cur+1)
            for elem in y_next:
                cur_path_pre=cur_path+[triangle[x_next][elem]]
                self.bfs(all_paths,cur_path_pre,[x_next,elem],triangle)
        else:
            all_paths.append(cur_path)
动态规划,简练:
class Solution(object):
    def minimumTotal(self, triangle):
        dp=triangle[-1][:]
        # print(dp)
        for i in  range(len(triangle)-2,-1,-1):
            for j in range(i+1):
                # print(i,j)
                dp[j]=min(dp[j],dp[j+1])+triangle[i][j]
                # dp=dp[:i+1]
        return dp[0]
    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000014306327
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞