-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadditiveNumber.cpp
More file actions
43 lines (40 loc) · 1.29 KB
/
additiveNumber.cpp
File metadata and controls
43 lines (40 loc) · 1.29 KB
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
36
37
38
39
40
41
42
43
// Source: https://leetcode.com/problems/additive-number/
// Author: Miao Zhang
// Date: 2021-02-01
class Solution {
public:
bool isAdditiveNumber(string num) {
vector<long long> path;
long_max = to_string(LLONG_MAX);
return dfs(num, 0, num.size(), path);
}
private:
string long_max;
bool isValid(vector<long long> &path) {
if (path.size() < 3) return false;
for (int i = 2; i < path.size(); i++) {
long long a = path[i - 2];
long long b = path[i - 1];
long long c = path[i];
if (a + b != c) return false;
}
return true;
}
bool dfs(string &s, int start, int n, vector<long long> &path) {
if (start == n) {
return isValid(path);
}
for (int i = 1; i <= n - start; i++) {
if (s[start] == '0' && i > 1) break;
string cur = s.substr(start, i);
if (cur.size() > long_max.size() || cur.size() == long_max.size() && cur.compare(long_max) > 0) break;
path.push_back(stoll(cur));
if ((path.size() > 2 && !isValid(path)) || !dfs(s, start + i, n, path)) {
path.pop_back();;
} else {
return true;
}
}
return false;
}
};