0

I have attached the solution here. 1st one works but the second doesn't. The only change is I have moved the result variable as an attribute with global scope to a parameter in the helper function.

Question: I understand that in 2nd case I am not updating the result which is passed as a parameter because I am not updating the result variable like so:

int i=0;
i = modifyValue(i);

Does this mean that attributes or class fields are passed by reference, as in 1st solution?

Sol1:

class Solution {
    int result = 0;
    
    public int findTargetSumWays(int[] nums, int S) {
        if (nums == null || nums.length == 0) return result;
        helper(nums, S, 0, 0);
        return result;
    }
    
    public void helper(int[] nums, int target, int pos, long eval){
        if (pos == nums.length) {
            if (target == eval) result++;
            return;
        }
        helper(nums, target, pos + 1, eval + nums[pos]);
        helper(nums, target, pos + 1, eval - nums[pos]);
    }
}

Sol2:

class Solution {
    
    public int findTargetSumWays(int[] nums, int S) {
        int result = 0;
        if (nums == null || nums.length == 0) return result;
        helper(nums, S, 0, 0, result);
        return result;
    }
    
    public void helper(int[] nums, int target, int pos, long eval, int result){
        if (pos == nums.length) {
            if (target == eval) result++;
            return;
        }
        helper(nums, target, pos + 1, eval + nums[pos], result);
        helper(nums, target, pos + 1, eval - nums[pos], result);
    }
}
alpha
  • 1

0 Answers0