给出一串数字字符串,比如”112358”,它可以这样子构造
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8;
“199100199”
1 + 99 = 100, 99 + 100 = 199
存在如下的限制
比如字符串1023 不能构成 1 + 02 = 3的形式,前面不能有前导0
直接暴力搜索。深度优先
import java.math.BigDecimal;
import java.math.BigInteger;
public class Solution {
static String num = null;
public boolean isAdditiveNumber(String num) {
Solution.num = num;
boolean flag = false;
flag = func();
return flag;
}
private static boolean func(){
boolean flag = false;
for(int i = 1; i < num.length(); ++i){
for(int j = 1; j + i < num.length(); ++j){
flag = isOk(0, i, i + j);
if(flag == true){
return flag;
}
}
}
return flag;
}
private static boolean isOk(int s1, int s2, int s3){
if(check(s1, s2) == false || check(s2, s3) == false){
return false;
}
BigInteger a = new BigInteger(num.substring(s1, s2));
BigInteger b = new BigInteger(num.substring(s2, s3));
for(int i = s3 + 1; i <= num.length(); ++i){
if(check(s3, i) == false){
return false;
}
BigInteger c = new BigInteger(num.substring(s3, i));
if(a.add(b).equals(c)){
if(i == num.length())return true;
else return isOk(s2, s3, i);
}
else if(a.add(b).compareTo(c) < 0){
return false;
}
}
return false;
}
private static boolean check(int s1, int s2){
return !(num.charAt(s1) == '0' && s2 - s1 > 1);
}
}