Java Solutions use List


  • 0
    Z

    It just like the previous problem which we want to get a list<list<>>.

    class Solution {
        public boolean isAdditiveNumber(String num) {
            if(num == null || num.length() == 0) return false;
            List<List<Long>> res = new ArrayList<>();
            List<Long> prev = new ArrayList<>();
            
            addList(res, num, prev, 0);
            System.out.println(res);
            
            if(res.size() > 0) return true;
            else return false;
        }
        
        private void addList(List<List<Long>> res, String num, List<Long> prev, int start){
            if(start == num.length()){
                if(prev.size() > 2) res.add(new ArrayList(prev));
                return;
            }
            if(num.charAt(start) == '0'){
                if(prev.size() < 2 || prev.get(prev.size() - 2) + prev.get(prev.size() - 1) == 0) {
                    prev.add((long) 0);
                    addList(res, num, prev, start + 1);
                    prev.remove(prev.size() - 1);
                }
                return;
            }
            
            for(int i = start + 1; i <= num.length(); i ++){
                if(res.size() > 0) break;
                if(i - start > num.length() / 2 || i - start >= 11) continue;
                if(prev.size() < 2){
                    prev.add(Long.parseLong(num.substring(start, i)));
                    addList(res, num, prev, i);
                    prev.remove(prev.size() - 1);
                }
                else if(prev.get(prev.size() - 1) + prev.get(prev.size() - 2) == Long.parseLong(num.substring(start, i))){
                    prev.add(Long.parseLong(num.substring(start, i)));
                    addList(res, num, prev, i);
                    prev.remove(prev.size() - 1);   
                }    
            }
        }
    }
    111

Log in to reply
 

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