题目描述:
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 sequence1, 2, 03
or1, 02, 3
is invalid.
Given a string containing only digits '0'-'9'
, write a function to determine if it's an additive number.
即给定一个由数字组成的字符串, 将这个字符串切割为至少三个部分并构成数字(不能包含前导0), 使得除了前两个元素外,每个元素等于它的前两个元素之和.
解题思路:
题目的主要困难点在于如何确定分割点.
我使用了递归的方式, 将大问题分割为小问题.
定义函数
bool exist(int i, int j,int k,vector<int>& a,vector<int>& b,string &s);
记a+b=c
其中a为字符串[i,j)构成的数字
b为字符串[j,k)构成的数字
此时求和得到c
再从下标c开始, 判断子符串[k,x)是否能构成数字c
若能构成数字c, 那么下一次的判断是a: [j, k), b:[k, x),
递归的结束条件为x == s.size(), 也就是字符串最后一个位置+1
初始化的时候, 枚举j和k的值即可, 判断是否能够构成Additive Number.
算法的时间复杂度为O(n^3).
参考代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool exist(int i, int j,int k,vector<int>& a,vector<int>& b,string &s){
if (k == s.size())return true;
//a+b=c
//a belong to s[i,j)
//b belong to s[j,k)
vector<int> c;
int carry = 0;
for (int ii=0,jj=0;carry||ii<a.size()||jj<b.size();++ii,++jj){
if (ii < a.size())carry += a[ii];
if (jj < b.size())carry += b[jj];
c.push_back(carry % 10);
carry /= 10;
}
int t = k;
for (int y = c.size()-1;y >= 0;--y){
if (t >= s.size())return false;
int h = s[t++] - '0';
if (h != c[y])return false;
}
return exist(j,k,k+c.size(),b,c,s);
}
vector<int> getNum(int i, int j, string &s){
//[i,j)
vector<int> v;
for (int k = j-1;k>=i;--k){
v.push_back(s[k] - '0');
}
return v;
}
bool isAdditiveNumber(string num) {
if (num.size() < 3)return false;
for (int j = 1;j < num.size();++j){
for (int k = j+1;k < num.size();++k){
if (num[j] == '0' && (k-j)>1)break;
vector<int> a = getNum(0,j,num);
vector<int> b = getNum(j,k,num);
if (exist(0,j,k,a,b,num)){
return true;
}
}
}
return false;
}
};