Below is my function which gives all the possibilities that the elements in a given array sums up to a specific target. I am able to print the lists, however the result list is not getting updated.
public List<List<Integer>> helper(List<List<Integer>> res, int[] c, int l, int h, int target, List<Integer> temp){
if(target == 0){
res.add(temp);
System.out.println(temp);
return res;
}
if(target < c[l]){
return res;
}
for(int i = l; i <=h; i++){
temp.add(c[i]);
res = helper(res, c,i,h,target-c[i], temp);
temp.remove(temp.size()-1);
}
return res;
}
res is arraylist of empty arraylists in the end, but the 5th line prints the temp arraylist correctly.
The function is called as below.
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
res = helper(res,candidates, 0, candidates.length-1, target, temp);
Example: Given array = [1,2,3], target = 6
stdout:
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 2]
[1, 1, 1, 3]
[1, 1, 2, 2]
[1, 2, 3]
[2, 2, 2]
[3, 3]
res is [[],[],[],[],[],[],[]]