美文网首页
Leetcode-120Triangle

Leetcode-120Triangle

作者: LdpcII | 来源:发表于2018-04-18 13:10 被阅读0次

    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.

    For example, given the following triangle

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

    My Solution(C/C++)

    #include <cstdio>
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class Solution {
    public:
        //vector<vector<int>> minimumTotal(vector<vector<int>> &triangle) {
        int minimumTotal(vector<vector<int>> &triangle) {
            int row = triangle.size();
            vector<vector<int>> dp(row, vector<int>());
            for (int i = row - 1; i >= 0; i--) {
                for (int j = 0; j < triangle[i].size(); j++) {
                    if (i == row - 1) {
                        dp[i].push_back(triangle[i][j]);
                    }
                    else {
                        dp[i].push_back(triangle[i][j] + min(dp[i + 1][j], dp[i + 1][j + 1]));
                    }
                }
            }
            //return dp;
            return dp[0][0];
        }
    };
    
    int main() {
        vector<vector<int>> triangle(4, vector<int>());
        triangle[0].push_back(2);
        triangle[1].push_back(3);
        triangle[1].push_back(4);
        triangle[2].push_back(6);
        triangle[2].push_back(5);
        triangle[2].push_back(7);
        triangle[3].push_back(4);
        triangle[3].push_back(1);
        triangle[3].push_back(8);
        triangle[3].push_back(3);
        //printf("%d ", triangle[1][1]);
        Solution s;
        //vector<vector<int>> dp;
        //dp = s.minimumTotal(triangle);
        //for (int i = 0; i < dp.size(); i++) {
        //  for (int j = 0; j < dp[i].size(); j++) {
        //      printf("%d ", dp[i][j]);
        //  }
        //  printf("\n");
        //}
        printf("三角形最小路径和:%d", s.minimumTotal(triangle));
        return 0;
    }
    

    My Solution(Python)

    class Solution:
        def minimumTotal(self, triangle):
            """
            :type triangle: List[List[int]]
            :rtype: int
            """
            row = len(triangle) - 1
            column = len(triangle[len(triangle)-1]) - 1
            dp = [[] for i in range(row + 1)]
            for i in range(column + 1):
                dp[row].append(triangle[row][i])
            for r in range(row - 1, -1, -1):
                for c in range(len(triangle[r])):
                    dp[r].append(min(dp[r+1][c], dp[r+1][c+1]) + triangle[r][c])
            return dp[0][0]
    
    

    相关文章

      网友评论

          本文标题:Leetcode-120Triangle

          本文链接:https://www.haomeiwen.com/subject/fcyvkftx.html