Title Link: 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 and numbers, each subsequent number in the sequence must is the sum of the preceding.
for example:
" 112358 "
is an additive number because the digits can form an additive seq Uence: 1, 1, 2, 3, 5, 8
.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199"
is also a 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, style=
or 1, 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 handle overflow for very large input integers?
Idea: A basic idea is that after the first and second numbers are determined, the subsequent number is verified, so as long as the first and second numbers are enumerated, and then constantly verify that the following string substring is the first two numbers and can. Because the number may be outside the range of integers, you can add a string to simulate the addition of integers when verifying that a number is another two sum. Another thing to note is the ' 0 ' character, if he is at the top of the substring, then he can only exist in the form of "0", and "0" may only be the first or second number.
The code is as follows:
Class Solution {public:string Add (string s1, string s2) {string result; int flag = 0, i = s1.size ()-1, J = s2.size ()-1; while (I >=0 | | J >=0) {int num1=0, num2=0; if (i >=0) num1 = s1[i]-' 0 '; if (J >= 0) num2 = s2[j]-' 0 '; Result.insert (Result.begin (), ' 0 ' + (num1+num2+flag)%10); Flag = (Num1+num2+flag)/10; I--, j--; } if (flag = = 1) result.insert (Result.begin (), ' 1 '); return result; } bool DFS (String num, String num1, String num2) {if (Num.size () ==0 | | num[0] = = ' 0 ') return false; for (int i =0; i < num.size (); i++) {string x = Num.substr (0, i+1); if (x ==add (num1,num2)) {if (i = = Num.size ()-1) return true; Return DFS (Num.substr (i+1), num2, X); }} return false; } bool Isadditivenumber (string num) {int len = Num.size(); if (Len < 3) return false; String Num1, num2; for (int i = 0; i < len-2; i++) {num1 = num.substr (0, i+1); for (int j = i+1; J < Len-1; J + +) {num2 = Num.substr (i+1, j-i); if (DFS (Num.substr (j+1), NUM1, num2)) return true; if (num[i+1] = = ' 0 ') break; } if (num[0] = = ' 0 ') break; } return false; }};
[Leetcode] 306. Additive Number Problem Solving report