您的位置:首页 > 其它

306. Additive Number 自己写的,居然ac了,写一遍比看100遍强,看别人对边界的处理纯属浪费时间,不如自己动手,自己手写才能提高

2017-08-26 13:49 656 查看
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?

Credits:

Special thanks to @jeantimex for adding this problem and creating all test cases.

class Solution {
public:
bool isAdditiveNumber(string num) {

for(int i=0;i<num.size()/3+1;i++){
string s1=num.substr(0,i-0+1);
long l1=stol(s1);
string tmp=to_string(l1);

if(s1.size()==tmp.size()){
for(int j=i+1;j<num.size()/3*2+1;j++){
string s2=num.substr(i+1,j-(i+1)+1);
long l2=stol(s2);
string tmp=to_string(l2);
if(s2.size()==tmp.size()){
bool sum_flag=false;

if(dp(l1,l2,i,j,num,sum_flag))
return true;
}
}
}

}
return false;
}
bool dp(long first,long second,int i,int j,string num,bool sum_flag){
if(sum_flag==true&&(j==num.size()-1)){
return true;
}
else if(j==num.size()-1){
return false;
}
long ans=first+second;
string ans_s=to_string(ans);
int len=ans_s.size();
if(j+1+len-1>num.size()-1){
return false;
}
string num_sub=num.substr(j+1,len);

if(ans_s==num_sub){
sum_flag=true;
return dp(second,ans,j,j+1+len-1,num,sum_flag);
}
return false;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: