您的位置:首页 > 其它

LeetCode 306. Additive Number(加法的数字)

2016-04-20 01:13 387 查看
原题网址: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 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?
方法:深度优先搜索。

public class Solution {
private boolean additive;
private void dfs(String num, int from, long[] nums, int step) {
if (additive) return;
if (from == num.length()) {
if (step >= 3) additive = true;
return;
}
for(int i=from+1; i<=from+19 && i<=num.length(); i++) {
nums[step] = Long.parseLong(num.substring(from, i));
if (step < 2) {
dfs(num, i, nums, step+1);
} else {
if (nums[step-2]+nums[step-1]==nums[step]) dfs(num, i, nums, step+1);
}
if (num.charAt(from)=='0') break;
}

}
public boolean isAdditiveNumber(String num) {
dfs(num, 0, new long[num.length()], 0);
return additive;
}
}


优化:

public class Solution {
private boolean find(String num, int a, int b, int c) {
if (c == num.length()) return true;
long na = Integer.parseInt(num.substring(a, b), 10);
long nb = Integer.parseInt(num.substring(b, c), 10);
long nc = na + nb;
String sc = Long.toString(nc);
if (c+sc.length() > num.length()) return false;
if (!sc.equals(num.substring(c, c+sc.length()))) return false;
a = b;
b = c;
c += sc.length();
return find(num, a, b, c);
}
public boolean isAdditiveNumber(String num) {
if (num == null || num.length() < 3) return false;
for(int i=1; i<(num.length()+1)/2 && i<12; i++) {
for(int j=i+1; num.length()-j>=Math.max(i, j-i) && j-i<12; j++) {
if (find(num, 0, i, j)) return true;
if (num.charAt(i) == '0') break;
}
if (num.charAt(0) == '0') break;
}
return false;
}
}


其他改进:尽可能引入更多的剪枝条件;手工实现加法以便处理特别大的数字,用BigInteger来处理大数字。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: