0ms Java Recursive Solution


  • 1
    A

    Tried adding some explanation. Let me know if something is unclear or if it could be improved to be more concise.

    public class Solution {
        
        
        boolean compute(String s, int pos, long first, long sec, int numbers) {
            if(pos == s.length()) {
                return numbers > 2;
            }
            // Handling numbers starting with 0. if it's one of the first two,
            // or the sum of previous two is 0, then it's allowed;
            // Otherwise, you cannot start a number with 0;
            if(s.charAt(pos) == '0') {
                if(numbers < 2) return compute(s, pos + 1, sec, 0, numbers + 1);
                else if(first + sec == 0) return compute(s, pos + 1, sec, 0, numbers + 1);
                return false;
            }
            long num = 0;
            boolean ans = false;
            for(int i = pos; i < s.length(); i++) {
                // Try to take a chunk out and recursively call on rest of the number.
                num = num * 10 + (s.charAt(i) - '0');
                if(numbers < 2 || num == first + sec)
                    ans |= compute(s, i + 1, sec, num, numbers + 1);
            }
            return ans;
        }
        
        
        public boolean isAdditiveNumber(String num) {
            return compute(num, 0, -1, -1, 0);
        }
    }
    

  • 0
    Y
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.