Leetcode[306] Additive Number
08 Dec 2015###Task1 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?
###Java
public class Solution {
public boolean isAdditiveNumber(String num) {
if (num == null || num.length() == 0) {
return false;
}
String a;
String b;
for (int i = 0; i < num.length() / 3; i++) {
a = num.substring(0, i + 1);
if (a.charAt(0) == '0' && a.length() > 1) {
continue;
}
for (int j = i + 1; j < num.length(); j++) {
b = num.substring(i + 1, j + 1);
if (b.charAt(0) == '0' && b.length() > 1) {
continue;
}
if (isValid(num.substring(j + 1), Long.parseLong(a), Long.parseLong(b))) {
return true;
}
}
}
return false;
}
public boolean isValid(String num, long a, long b) {
String result = String.valueOf(a + b);
if (result.length() > num.length()) {
return false;
}
if (result.length() == num.length() && result.equals(num)) {
return true;
}
if (result.equals(num.substring(0, result.length()))) {
return isValid(num.substring(result.length()), b, a + b);
}
return false;
}
}
###Points
- DP is not panacea
- Sometimes enumeration is the only choice. Why? cannot figure out the dp function, need backtracking.