这道题的关键在于想到
dp[i][j] = min(dp[i-1][j-1] , dp[i-1][j]) + triangle[i][j];
太久没做过算法题了,连设一个dp数组都没意识到
我的代码
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { int size = triangle.size(); if(size==1) return triangle[0][0]; vector<vector <int> > dp(size,vector<int>(size)); dp[0][0] = triangle[0][0]; for(int i = 1;i < size;i++) { for(int j = 0;j <= i ;j++) { if(j == 0) dp[i][j] = dp[i-1][j] + triangle[i][j]; else if(j == i) dp[i][j] = dp[i-1][j-1] + triangle[i][j]; else dp[i][j] = min(dp[i-1][j-1] , dp[i-1][j]) + triangle[i][j]; } } int res = dp[size-1][0]; for(int i = 1;i <= size-1 ; i++) res = min(res,dp[size-1][i]); return res; } };
标签:vector,triangle,int,路径,leetcode120,三角形,dp,size From: https://www.cnblogs.com/uacs2024/p/18059428