问题描述
我试图了解Java对象引用。到目前为止,我学到的是
- 对象的引用按值传递,因此在方法返回后,可以在该对象中添加一些内容。
- 在将对象foo作为参数接收的方法中创建新对象foo不会反映对本地foo对象和传递的foo对象所做的更改。
基于此知识,我试图理解 为什么以下代码段未从已添加到结果列表的当前列表中删除对象。
下面的代码在递归结束时不会出现空列表,即使将currentList的引用添加到resultList并且我们正在从currentList中删除元素。
findCombations(condidates,target,new ArrayList<Integer>(),result);
public void findCombinations(int[] candidates,int index,Int target,List<Integer> currentList,List<List<Integer» result) {
if(target == 0) {
result.add(currentList);
return;
}
if(target < 0) { return; }
for(int i = index; i < candidates.length; i++) {
if(i == index && candidates[i] != candidates[i - 1]) {
currentList.add(candidates[i]);
findCombinations(candidates,i + 1,target - candidates[i],currentList,result);
currentList.remove(currentList.size() - 1); //why removing numbers from this list not removing the numbers from the currentList that's been added to result list?
}
}
有人可以帮我理解这种行为吗?
编辑:
这是一个leetcode问题,需要独特的组合才能导致目标: 我们必须找到所有唯一的数字组合,它们的和导致给定的目标。我们不能有重复的集合/组合。 提供的代码在给定的数组上执行DFS,并基于减去数组中遇到的元素来查找组合。有2种基本情况,当目标== 0时,我们仅将currentList添加到resultList中。 CurrentList包含其和== target的数字,另一个基本情况是target
Input: candidates = [10,1,2,7,6,5],target = 8,A solution set is:
[
[1,7],[1,[2,6],6]
]
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)