有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解释了“ans.add(new ArrayList<>(temp))”和“ans.add(temp)”之间的区别

这是一种回溯算法,可以找到数组num中的所有子集。 为什么我不能在函数回溯中直接使用“ans.add(temp)”, 但必须使用“ans.add(new ArrayList<;gt;(temp))”

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans=new ArrayList<>(); 
        List<Integer> temp=new ArrayList<>(); 
        Backtracking(0,nums,ans,temp);
        return ans;
    }
    private void Backtracking(int i,int[] nums,List<List<Integer>> ans,List<Integer> temp)
    {
        ans.add(new ArrayList<>(temp));    // Why can't I use “ans.add(temp)”???
        for(int j=i;j<nums.length;j++)
        {
            temp.add(nums[j]);
            Backtracking(j+1,nums,ans,temp);
            temp.remove(temp.size()-1);
        }  
    }
}

共 (0) 个答案