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);
}
}
}