-1

I was trying to solve this problem from leetcode - https://leetcode.com/problems/combination-sum/

My test case is

Input = [1]
Result = 1

However, it is returning empty result. I think the code is doing fine. I mean the function getCombinations does add the value 1 to the result. But ultimately combinationSum return empty result. I think it has to do with something related to pass by reference or something. Any ideas what could have gone wrong?

public class Solution {
    public List<List<Integer>> combinationSum(int[] a, int target) {
        Arrays.sort(a);
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        ArrayList<Integer> current = new ArrayList<Integer>();
        getCombinations(0, a, result, target,current);
        return result;
    }

    public void getCombinations(int start, int[] a, List<List<Integer>> result, int target, ArrayList<Integer> current) {
        if(target == 0) {
            result.add(current);
            return;
        }
        if(target < 0) {
            return;
        }
        for(int i=start;i<a.length; i++) {
            current.add(a[i]);
            getCombinations(i+1, a, result,target-a[i],current);
            current.remove(current.size()-1);
        }
    }
}
Eric Darchis
  • 24,537
  • 4
  • 28
  • 49
rajan sthapit
  • 4,194
  • 10
  • 42
  • 66
  • 6
    Your biggest issue with pass-by-reference in Java is the fact the language doesn't support it. – Andy Turner Apr 17 '16 at 22:04
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) –  Apr 17 '16 at 22:12
  • The desired behavior is that result contains [1], the code to reproduce that is in the question. – fgb Apr 17 '16 at 22:38

1 Answers1

1

You need to create a copy of current when adding to result like:

result.add(new ArrayList<>(current));

otherwise, when the items are removed from current, then they will be removed from the result too.

fgb
  • 18,439
  • 2
  • 38
  • 52