传递的只是地址而已。只有将temp拷贝一份,才不影响原来的temp。 关注点在于容器的拷贝
class Solution {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(candidates,target,new ArrayList<Integer>(),0);
return ans;
}
void dfs(int[] candidates,int target,List<Integer> temp,int pos){
if(target==0){
ans.add(new ArrayList(temp));
return;
}
for(int i=pos;i<candidates.length&&candidates[i]<=target;++i){
temp.add(candidates[i]);
dfs(candidates,target-candidates[i],temp,i);
temp.remove(temp.size()-1);
}
}
}