版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/artisans/article/details/89189479
class Solution {
public:
#define ll long
#define atoll atol
bool isAdditiveNumber(string num) {
_num = num;
_flags = vector<int>(num.size(), 0);
_flags[0] = 1;
dfs(1);
return _ret;
}
void dfs(int i)
{
if (i == _num.size())
{
handle();
}
else
{
_flags[i] = 0;
if(promise1(i))
dfs(i + 1);
_flags[i] = 1;
if (promise2(i))
dfs(i + 1);
}
}
bool promise1(int index)
{
bool bb;
vector<ll> vec = flag_to_vec(bb);
if (bb == false) return false;
if (vec.size() == 1 && index >= _num.size() - 2)
{
return false;
}
else if(vec.size() == 2)
{
if (vec[0] > vec[1]) return false;
}
return true;
}
bool promise2(int index)
{
vector<ll> vals;
int pre = 0;
for (size_t i = 1; i <= index; i++)
{
if (_flags[i])
{
string TMP(_num.begin() + pre, _num.begin() + i);
//出现以0开头的数字
if (TMP[0] == '0' && TMP.size() > 1)
{
return false;
}
vals.push_back(atoll(TMP.c_str()));
pre = i;
}
}
if (vals.size() >= 3)
{
ll p1 = vals[0], p2 = vals[1];
for (int i = 2; i < vals.size(); i++)
{
if (vals[i] != p1 + p2)
{
for (int v : vals)
{
//cout << v << "\t";
}
//cout << "\n";
return false;
}
p1 = p2, p2 = vals[i];
}
}
return true;
}
vector<ll> flag_to_vec(bool& bb)
{
vector<ll> vals;
int pre = 0;
for (size_t i = 1; i < _flags.size(); i++)
{
if (_flags[i])
{
string TMP(_num.begin() + pre, _num.begin() + i);
//出现以0开头的数字
if (TMP[0] == '0' && TMP.size() > 1)
{
bb = false;
}
vals.push_back(atoll(TMP.c_str()));
pre = i;
}
}
string TMP(_num.begin() + pre, _num.end());
vals.push_back(atoll(TMP.c_str()));
//出现以0开头的数字
if (TMP[0] == '0' && TMP.size() > 1)
{
bb = false;
}
return vals;
}
void handle()
{
bool bb = true;
//if (_flags[0] == 1 && _flags[1] == 1 && _flags[11] == 1)
//{
// //for (int v : vals)
// //{
// // cout << v << "\t";
// //}
// //cout << "\n";
//}
vector<ll> vals = flag_to_vec(bb);
if (bb && vals.size() >= 3)
{
#ifdef PRINT
for (int v : vals)
{
cout << v << "\t";
}
cout << "\n";
#endif
ll p1 = vals[0], p2 = vals[1];
for (size_t i = 2; i < vals.size(); i++)
{
if (vals[i] != p1 + p2)
{
break;
}
else
{
p1 = p2, p2 = vals[i];
}
if (i == vals.size() - 1)
{
#ifdef PRINT
cout << "==========\t";
for (int v : vals)
{
cout << v << "\t";
}
cout << "\n";
#endif
_ret = true;
}
}
}
}
bool _ret = false;
vector<int> _flags;
string _num;
};