Skip to content

Commit a5c54d4

Browse files
committed
Update #306 Additive Number.java
1 parent 92761bb commit a5c54d4

File tree

1 file changed

+44
-20
lines changed

1 file changed

+44
-20
lines changed

#306 Additive Number.java

Lines changed: 44 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// Some bugs;
22

3-
43
import java.util.*;
54

65
public class Solution {
@@ -15,48 +14,73 @@ public boolean isAdditiveNumber(String num) {
1514
this.num = num;
1615
int max = Math.min(num.length() / 2, 9);
1716

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))
17+
// System.out.println("max: " + max);
18+
19+
if(num.charAt(0) == '0'){
20+
if(num.charAt(1) == '0'){
21+
if(dfs(0, 0, 1, 2))
2322
return true;
2423
}
24+
else
25+
for(int j = 0; j < max; j++){
26+
int prepre = 0;
27+
int pre = Integer.parseInt(num.substring(1, j + 2));
28+
if(dfs(prepre, pre, j + 1, j + 2))
29+
return true;
30+
}
31+
} else {
32+
for(int i = 0; i < max; i++){
33+
if(num.charAt(i + 1) == '0'){
34+
if(dfs(Integer.parseInt(num.substring(0, i + 1)), 0, i + 1, i + 2))
35+
return true;
36+
}
37+
else
38+
for(int j = 0; i + j < max && j < max; j++){
39+
int prepre = Integer.parseInt(num.substring(0, i + 1));
40+
int pre = Integer.parseInt(num.substring(i + 1, i + j + 2));
41+
if(dfs(prepre, pre, Math.max(i, j) + 1, i + j + 2))
42+
return true;
43+
}
44+
}
45+
}
46+
2547

2648
return false;
2749
}
2850

2951
private boolean dfs(int prepre, int pre, int digits, int idx) {
30-
31-
// System.out.println(prepre + " " + pre + " " + digits + " " + idx);
32-
52+
53+
// System.out.println("prepre: " + prepre + " pre: " + pre + " digits: " + digits + " idx: " + idx);
54+
3355
if(idx >= num.length())
3456
return true;
35-
57+
3658
if(num.charAt(idx) == '0' && digits > 1)
3759
return false;
3860

3961
if(num.length() - idx < digits)
4062
return false;
41-
63+
4264
boolean res = false;
43-
65+
4466
// digits
4567
int pos = Integer.parseInt(num.substring(idx, idx + digits));
46-
if(pos == prepre + pre)
68+
if(pos == prepre + pre){
4769
res = dfs(pre, pos, digits, idx + digits);
48-
70+
}
71+
4972
if(res)
50-
return res;
51-
73+
return true;
74+
5275
// digits + 1;
53-
if(idx + digits + 1 <= num.length() && digits < 9){
76+
if(num.charAt(idx) != '0' && idx + digits + 1 <= num.length() && digits < 9){
5477
int poss = Integer.parseInt(num.substring(idx, idx + digits + 1));
55-
if(poss == prepre + pre)
78+
if(poss == prepre + pre){
5679
res = dfs(pre, poss, digits + 1, idx + digits + 1);
80+
}
5781
}
58-
59-
82+
83+
6084
return res;
6185
}
6286
}

0 commit comments

Comments
 (0)