下面是我的函数,它给出了给定数组中的元素总和达到特定目标的所有可能性。我可以打印列表,但是结果列表没有更新。
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;
}
Run Code Online (Sandbox Code Playgroud)
res 最后是空数组列表的数组列表,但第 5 行正确打印临时数组列表。
该函数的调用如下。
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
res = helper(res,candidates, 0, candidates.length-1, target, temp);
Run Code Online (Sandbox Code Playgroud)
示例:给定数组 = [1,2,3],目标 = 6
标准输出:
[1, 1, 1, 1, 1, …Run Code Online (Sandbox Code Playgroud)