问题描述:这里写链接内容
问题分析:这道题比较直观,就是采用回溯法。
代码如下:2ms
public class Solution {
char[] chars;
String num;
public boolean isAdditiveNumber(String num) {
chars = num.toCharArray();
this.num = num;
return dfs(0,0,"","");
}
/**
base:当前回溯的起始点
totals:总归有多少对了
prevIndex:上个数的初始点
*/
private boolean dfs(int base,int total,String prevprev,String prev){
if(base == chars.length){
if(total > 2)
return true;
return false;
}
if(prevprev.length() != 0 && prev.length() !=0){
String needSum = sumOfStr(prevprev,prev);
int endBase = needSum.length() + base;
if(endBase > chars.length)
return false;
String compSum = num.substring(base,endBase);
if(compSum.equals(needSum)){
return dfs(endBase,total+1,prev,compSum);
}
return false;
}
for(int i = base;i<chars.length;i++){
if(chars[base] == '0' && i > base)//0 can not be the leading zero
break;
String value = num.substring(base,i+1);
if(prevprev.length() == 0){
if(dfs(i+1,total+1,value,prev))
return true;
}
else if(prev.length() == 0){
if(dfs(i+1,total+1,prevprev,value))
return true;
}
}
return false;
}
private String sumOfStr(String num1,String num2){
char[] chars1 = num1.toCharArray();
char[] chars2 = num2.toCharArray();
StringBuilder builder = new StringBuilder();
int chars1Index = chars1.length-1;
int chars2Index = chars2.length-1;
int prev = 0;
while(chars1Index >= 0 && chars2Index >= 0){
int value = chars2[chars2Index--] -'0' + chars1[chars1Index--] - '0' + prev;
builder.append(value % 10);
prev = value / 10;
}
while(chars1Index >= 0){
int value = chars1[chars1Index--] - '0' + prev;
builder.append(value % 10);
prev = value / 10;
}
while(chars2Index >= 0){
int value = chars2[chars2Index--] - '0' + prev;
builder.append(value % 10);
prev = value / 10;
}
if(prev!=0)
builder.append(prev);
return builder.reverse().toString();
}
}