Java Straight Forward Solution

  • 0
    public int findTargetSumWays(int[] nums, int S) {
            HashMap<Integer, Integer> inter = new HashMap<>();
            for(int n : nums){
                HashMap<Integer, Integer> tmp = new HashMap<>();
                if(inter.size() == 0){
                    inter.put(n, 1);
                    inter.put(-n, inter.getOrDefault(-n,0)+1);
                    for(Map.Entry<Integer, Integer> entry : inter.entrySet()){
                        tmp.put(entry.getKey()+n, tmp.getOrDefault(entry.getKey()+n,0)+entry.getValue());
                        tmp.put(entry.getKey()-n, tmp.getOrDefault(entry.getKey()-n,0)+entry.getValue());
                    inter = tmp;
            return inter.getOrDefault(S,0);

Log in to reply

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