Description
Solution
当类Fibonacci数列的前两项确定时,整个序列便确定了, 故我们只需要枚举前两项,在check一下是否合法即可
小模拟
Code
class Solution {
public:
#define inf 0x3f3f3f3f
int toint(string s) {
if(s.size() > 10) return -1;
long long res = 0;
for(int i = 0;i < s.size();++i) {
res = (res * 10 + (s[i] - '0'));
}
if(res > ((1ll*1<<31)-1)) return -1;
return (int)res;
}
vector<int> splitIntoFibonacci(string S) {
int sz = S.size();
vector<int>res;
for(int i = 1;i < sz;++i) {
for(int j = 1;i + j < sz;++j) {
string f1 = S.substr(0,i), f2 = S.substr(i,j);
if((i != 1 && f1[0] == '0') || (j != 1 && f2[0] == '0')) continue;
res.clear();
int x1 = toint(f1), x2 = toint(f2);
if(x1 == -1 || x2 == -1) continue;
res.push_back(x1);
res.push_back(x2);
int st = i + j;
bool flag = true;
for(int k = i + j;k < sz;++k) {
string tmp = S.substr(st, (k-st+1));
if((k-st+1) != 1 && tmp[0] == '0') {flag = false;break;}
int x3 = toint(tmp);if(x3 == -1) break;
if(1ll*x3 != (1ll*res[res.size()-1] + res[res.size()-2])) {continue;}
res.push_back(x3);
st = k+1;
}
if(st != sz) flag = false;
if(flag) return res; else res.clear();
}
}
return res;
}
};