在leetcode组合问题中,我尝试将列表添加到列表列表中,但结果是一个空列表列表。但是,当我创建一个与前一个列表相同的新列表,然后将新列表添加到列表列表中时,它会显示正确的答案。
List<Integer> t = new ArrayList<>(list); //this is making
result.add(t); //a new list and add it to result
为什么要制作新名单?
以下是leetcode给出的示例代码:
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
if(k == 0) return res;
bt(1, n, k, new ArrayList<Integer>());
return res;
}
private void bt(int start, int n, int k, List<Integer> list){
if(k == 0){
List<Integer> t = new ArrayList<>(list);
res.add(t);
return;
}
for(int i= start; i<=n; i++){
list.add(i);
bt(i+1, n, k-1, list);
list.remove(list.size()-1);
}
}
}