-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path306.AdditiveNumber.cpp
More file actions
70 lines (58 loc) · 1.42 KB
/
306.AdditiveNumber.cpp
File metadata and controls
70 lines (58 loc) · 1.42 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
long long getNum(string num, int start, int end) {
long long n = 0;
for(int i=start; i<=end; i++) {
n = n*10+num[i]-'0';
}
return n;
}
bool additive(string nums, int start) {
for(int i=start; i<int(nums.size())-2; i++) {
if(nums[start] == '0' && i-start+1 > 1) {
continue;
}
long long n1 = getNum(nums, start, i);
for (int j=i+1; j<int(nums.size())-1;j++){
if(i+1 < nums.size() && nums[i+1] == '0' && j-i > 1) {
continue;
}
long long n2 = getNum(nums, i+1, j);
for (int k=j+1; k<int(nums.size());k++) {
if(j+1 < nums.size() && nums[j+1] == '0' && k-j>1) {
continue;
}
int minBits = max(i-start+1, j-i);
int maxBits = minBits+1;
if(k-j > maxBits || k-j < minBits){
continue;
}
long long n3 = getNum(nums, j+1, k);
if(n1 + n2 != n3) {
continue;
}
if(k == nums.size()-1) {
return true;
}
if(additive(nums, i+1)) {
return true;
}
}
}
}
return false;
}
bool isAdditiveNumber(string num) {
return additive(num, 0);
}
};
int main() {
Solution s;
cout << s.isAdditiveNumber("101") << endl;
return 0;
}