Skip to content

Commit 92761bb

Browse files
committed
Create #306 Additive Number.java
1 parent dceb50d commit 92761bb

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

#306 Additive Number.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Some bugs;
2+
3+
4+
import java.util.*;
5+
6+
public class Solution {
7+
8+
String num;
9+
10+
public boolean isAdditiveNumber(String num) {
11+
12+
if(num == null || num.length() < 3)
13+
return false;
14+
15+
this.num = num;
16+
int max = Math.min(num.length() / 2, 9);
17+
18+
for(int i = 0; i < max; i++)
19+
for(int j = 0; j < max; j++){
20+
int prepre = Integer.parseInt(num.substring(0, i + 1));
21+
int pre = Integer.parseInt(num.substring(i + 1, i + j + 2));
22+
if(dfs(prepre, pre, Math.max(i, j) + 1, i + j + 2))
23+
return true;
24+
}
25+
26+
return false;
27+
}
28+
29+
private boolean dfs(int prepre, int pre, int digits, int idx) {
30+
31+
// System.out.println(prepre + " " + pre + " " + digits + " " + idx);
32+
33+
if(idx >= num.length())
34+
return true;
35+
36+
if(num.charAt(idx) == '0' && digits > 1)
37+
return false;
38+
39+
if(num.length() - idx < digits)
40+
return false;
41+
42+
boolean res = false;
43+
44+
// digits
45+
int pos = Integer.parseInt(num.substring(idx, idx + digits));
46+
if(pos == prepre + pre)
47+
res = dfs(pre, pos, digits, idx + digits);
48+
49+
if(res)
50+
return res;
51+
52+
// digits + 1;
53+
if(idx + digits + 1 <= num.length() && digits < 9){
54+
int poss = Integer.parseInt(num.substring(idx, idx + digits + 1));
55+
if(poss == prepre + pre)
56+
res = dfs(pre, poss, digits + 1, idx + digits + 1);
57+
}
58+
59+
60+
return res;
61+
}
62+
}

0 commit comments

Comments
 (0)