HashMap, Divide and Conquer, Java easy code


  • 0
    N
    class Solution {
        int totalSum = 0;
        public int pathSum(int[] nums) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i = 0; i < nums.length; i++) {
                map.put(nums[i] / 10, nums[i] % 10);
            }
            
            helper(nums[0] / 10, map, 0);
            
            return totalSum;
        }
        
        private void helper(int key, HashMap<Integer, Integer> map, int preSum) {
            int left = key + 10 + key % 10 - 1;
            int right = key + 10 + key % 10;
            
            int curSum = map.get(key) + preSum;
            
            if (!map.containsKey(left) && !map.containsKey(right)) {
                totalSum += curSum;
                return;
            }
            if (map.containsKey(left)) {
                helper(left, map, curSum);
            }
            if (map.containsKey(right)) {
                helper(right, map, curSum);
            }
        }
    }

Log in to reply
 

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