![](/img/trans.png)
[英]Convert ArrayList<ArrayList<Integer>> to List<List<Integer>>
[英]Inserting ArrayList<Integer> into List<List<Integer>>
我正在尝试解决 leetcode 问题https://leetcode.com/problems/combination-sum/我必须找出添加到指定数字的所有组合(组合存储在 ArrayList 中)。 我必须将所有组合 (ArrayList) 存储在 ArrayList 中。所以我将拥有 ArrayList 中的 ArrayList(称之为“ans”)。 但是我无法向这个 ans ArrayList 添加任何组合。我能够打印出所有组合,但我必须仅以 2d ArrayList 的形式返回它。 ans 列表在代码流结束时仅返回空列表。 我在下面附上我的代码
class Solution {
int[] candidates;
ArrayList<List<Integer>> ans;
void f(int index, int target, ArrayList<Integer> current){
if (target == 0){
System.out.println(current);
this.ans.add(current);
return;
}
if (target < 0) return;
for(int i = index; i < candidates.length; i++){
current.add(candidates[i]);
target -= candidates[i];
f(i, target, current);
target += candidates[i];
current.remove(current.size()-1);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.ans = new ArrayList<List<Integer>>();
this.candidates = candidates;
f(0, target, new ArrayList<>());
return this.ans;
}
}
输入: [2,3,6,7] 7
Output(ans 的内容): [[],[]]
标准输出: [2, 2, 3] [7]
@OH GOD SPIDERS,谢谢;。 发生这种情况是因为我没有将当前组合的副本传递给 ans 列表。 我不得不改变基本情况
if (target == 0){
this.ans.add(new ArrayList(current));
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.