0

If the input: int[] nums= [1,2,3], target=4; why the output res=0; the res has not been accumulated?

    public int combinationSum4(int[] nums, int target) {
        int res=0;
        helper(nums,target,res);
        return res;
    }

    private void helper(int[] nums, int target, int res){
        if (target==0) {
            res++;
            return;
        }
        else if (target<0) return;
        else {
            for(int i=0;i<nums.length;i++){
                helper(nums, target-nums[i],res);
            }
        }

    }
s666
  • 266
  • 1
  • 3
  • 14

1 Answers1

1

Java primitives are not passed by reference, but passed by values.
This means that if you pass an int to a method and increment it inside this method, the value is increased only in the scope of the method, not outside.

So res++ only changes res inside the helper method. if you want it to do anything outside of it, you need to return it's value and assign it outside

Nir Levy
  • 12,750
  • 3
  • 21
  • 38
  • Thanks, because I saw a piece of code written in C++, which is roughly the same as my code. So I was wondering whether C++ primitives are passed by values? (or is there something in C++, like "&", matters?) – s666 Oct 12 '19 at 21:50