老师好,关于remove有如下算法和问题:
题目描述:
https://leetcode.com/problems/combination-sum/
解答:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res= new ArrayList<>();
helper(res,candidates, target, new ArrayList<>(),0);
return res;
}
private void helper(List<List<Integer>> res, int[] nums, int target, List<Integer> temp, int start){
if(target==0){
res.add(new ArrayList<>(temp));
}else if(target <0) return;
for(int i=start;i<nums.length; i++){
temp.add(nums[i]);
helper(res, nums,target-nums[i], temp, i);
temp.remove(temp.size()-1);
}
}
}
我有两个问题:
1.
14行
temp.remove(temp.size()-1);
arraylist的remove方法可以输入index的方法,或者直接输入object来找到对应元素,并删除。
这里因为temp内本身往里面add的元素,也是integer,所以我不太懂,为什么在这里remove时,java会判定是按照index去remove(即remove掉最后一个元素),而不是去找temp.size()-1 对应的value,去remove temp里的元素呢?
2.
11行,
for(int i=start;i<nums.length; i++){
这里我一开始写成 int i =0;
我觉得虽然方法内部写错了,但算法本身应该没错,因为在第四行调用函数时,
helper(res,candidates, target, new ArrayList<>(),0);
start的初始值就是给的0,所以我觉得应该这里写int =0 也不会有错,但是程序结果有错,
当 int=0
输入:
[2,3,6,7]
7
输出为:
[[2,2,3],[2,3,2],[3,2,2],[7]]
但是改成int i= start后,输出为
[[2,2,3],[7]]
为正确结果。
我没搞懂为什么会出现这个差异?