题目链接:https://leetcode.com/problems/additive-number/
题目:
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
For example:
"112358"
is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8
.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199"
is also an additive number, the additive sequence is:
1, 99, 100, 199
.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03
or 1, 02, 3
is invalid.
Given a string containing only digits '0'-'9'
, write a function to determine if it's an additive number.
Follow up:
How would you handle overflow for very large input integers?
思路:
如果是additive number,则n1+n2=n3,n2+n3一定在字符串中,即可以递推,若不在,则不是additive number。
所以思路就是遍历找到第一、二个数,看它们是否满足上述条件。前导零的问题,以前做题的时候也遇到过,注意即可。
BigInteger要自己手动再AC代码前import java.math.BigInteger 否则会找不到此类。
算法:
public boolean isAdditiveNumber(String num) {
for(int i=1;i<num.length();i++){
if(i>1&&num.charAt(0)=='0')
return false;
BigInteger n1 = new BigInteger(num.substring(0,i));
for(int j=i+1;j<num.length();j++){
BigInteger n2 = new BigInteger(num.substring(i,j));
if(j>i+1&&num.charAt(i)=='0')
break;
if(isvalid(n1,n2,num.substring(j))){
return true;
}
}
}
return false;
}
private boolean isvalid(BigInteger n1, BigInteger n2, String num) {
if(num.length()==0)
return true;
BigInteger n3 = n2.add(n1);
return num.startsWith(n3.toString())&&isvalid(n2,n3,num.substring(n3.toString().length()));
}