leetcode-120-Triangle-等腰三角形

題目:app

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

示例:this

[
     [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.

題目解析:spa

1.此題是等腰三角形,上下之間的關係簡化爲上下相鄰的三個數,index相鄰,大小關係是在下方二選一+上方的數值,必然正確。 根據此思路,能夠top-bottom,或者bottom-top,因爲能夠簡化,因此動態規劃方法。   
2. 採用bottom-top方法,最後簡化爲1個值,因此左側值放置兩值中的小值。

代碼:code

普通代碼,較慢:
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]
相關文章
相關標籤/搜索