這個應該是一個典型的dp問題,用一個和輸入相同的二維數組進行到達此節點時的最小路徑。
注意兩個在每一行的邊界條件。以及row<=2時的處理,否則容易overflow.
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
vector<vector<int>> res = triangle;
int row(triangle.size());
if(row <=1) return triangle[0][0];
res[1][0] = res[1][0] + triangle[0][0];
res[1][1] = res[1][1] + triangle[0][0];
if(row <=2) return min(res[1][0], res[1][1]);
for(int i = 2; i < triangle.size(); i++){
for(int j = 0; j < triangle[i].size(); j++){
//cout << "i is:" << i << " j is:" << j <<endl;
if(j == 0 ){
res[i][j] = res[i-1][j] + triangle[i][j];
}
else if(j == triangle[i].size()-1){
res[i][j] = res[i-1][j-1] + triangle[i][j];
}
else{
res[i][j] = min(res[i-1][j], res[i-1][j-1]) + triangle[i][j];
}
}
}
int res_all = *min_element(res[row-1].begin(), res[row-1].end());
return res_all;
}
};