-
Notifications
You must be signed in to change notification settings - Fork 5
/
120. Triangle.cpp
35 lines (33 loc) · 981 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
29
30
31
32
33
34
35
// timeout
#include <climits>
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int res = INT_MAX;
vector <int> path;
DFS(triangle, path, res, 0, 0);
return res;
}
void DFS(vector<vector<int>>& triangle, vector <int> path, int &res, int location, int level)
{
if (path.size() == triangle.size())
{
int sum = accumulate(path.begin(), path.end(), 0);
if (sum < res)
res = sum;
return;
}
if (location < triangle[level].size())
{
path.push_back(triangle[level][location]);
DFS(triangle, path, res, location, level + 1);
path.pop_back();
}
if (location + 1 < triangle[level].size())
{
path.push_back(triangle[level][location + 1]);
DFS(triangle, path, res, location + 1, level + 1);
path.pop_back();
}
}
};