-
Notifications
You must be signed in to change notification settings - Fork 0
/
#120 Triangle.cpp
28 lines (26 loc) · 933 Bytes
/
#120 Triangle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
mMinLengths.resize(triangle.size(), vector<int>(triangle.back().size(), INT_MAX));
return minimumTotal(triangle, 0, 0);
}
private:
int minimumTotal(const vector<vector<int>>& triangle, size_t currRow, size_t currIdx) {
if (currRow == triangle.size() - 1) {
return triangle[currRow][currIdx];
}
else if (mMinLengths[currRow][currIdx] != INT_MAX) {
return mMinLengths[currRow][currIdx];
}
else {
int currMin = min(
minimumTotal(triangle, currRow + 1, currIdx),
minimumTotal(triangle, currRow + 1, currIdx + 1)
);
mMinLengths[currRow][currIdx] = currMin + triangle[currRow][currIdx];
return mMinLengths[currRow][currIdx];
}
}
private:
vector<vector<int>> mMinLengths;
};