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

原题网址: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来处理大数字。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值