LeetCode 120 Triangle DP
Given a triangle
array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i
on the current row, you may move to either index i
or index i + 1
on the next row.
Solution
基础的 \(DP\):用 \(dp[i][j]\) 表示到达 \((i,j)\) 的最小 \(sum\),转移方程为:
\[dp[i][j] = \min(dp[i-1][j-1],dp[i-1][j]) + a[i][j]
\]
注意边界即可
点击查看代码
class Solution {
private:
int dp[202][202];
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
if(n==1)return triangle[0][0];
else{
dp[0][0] = triangle[0][0];
int cnt = 1;
for(int i=1;i<n;i++){
cnt++;
for(int j=0;j<cnt;j++)dp[i][j]=1e5+1;
}
for(int i=1;i<n;i++){
for(int j=0;j<=i;j++){
if(j>=1 && j<i)dp[i][j] = min(dp[i-1][j-1],dp[i-1][j])+triangle[i][j];
else 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];
}
}
}
int ans=1e5+1;
for(int i=0;i<n;i++)ans = min(ans, dp[n-1][i]);
return ans;
}
}
};