Java Easy solution. HashMap


  • 0
    H
    class Solution {
        int res = 0;
        public int pathSum(int[] nums) {
            if(nums== null || nums.length == 0) return 0;
            HashMap<Integer,HashMap<Integer,Integer>> map = new HashMap<>();
            
            for(int i : nums){
                int val = i % 10;
                i = i / 10;
                int p = i % 10;
                i =  i /10;
                int d = i % 10;
                if(!map.containsKey(d)) map.put(d, new HashMap<>());
                map.get(d).put(p,val);
            }    
            
            helper(map,2,1,map.get(1).get(1));
            return res;
            
        }
        
        public void helper(HashMap<Integer,HashMap<Integer,Integer>> map, int dep, int pos,int sum){
            if(!map.containsKey(dep)){
                res += sum;
                return;
            }
            
            HashMap<Integer,Integer> temp = map.get(dep);
            
            if(!temp.containsKey(2*pos-1) && !temp.containsKey(2*pos)
               ){
                res += sum;
                return;
            }
            
           if(temp.containsKey(2*pos-1)){
                helper(map,dep+1,2*pos-1,sum + temp.get(2*pos-1));
            }
            
            if(temp.containsKey(2*pos)){
                helper(map,dep+1,2*pos,sum + temp.get(2*pos));
            }
        }
    }
    
    

Log in to reply
 

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