Subset (LeetCode)

Idea: Using the idea of ​​backtracking, each level has two choices, select the element or not select the element. If not, go directly to the next level. If you select, put the element into the list and go to the next level. layer, but in order to ensure that the branch that does not select the element exists, the element needs to be removed from the list. Continue making recursive calls. Finally, when the value of index is equal to the length of the array, the recursion stops. Load the list into res. The entire recursive process is a binary tree.

public class Subset {
    
    
    public List<List<Integer>> subsets(int[] nums) {
    
    
        List<List<Integer>> ans=new ArrayList<>();
        if (nums.length==0){
    
    
            return ans;
        }
        ArrayList<Integer> list=new ArrayList<>();
        dfs(ans,list,nums,0);
        return ans;
    }
    private void dfs(List<List<Integer>> res, List<Integer> temp, int[] nums, int index) {
    
    
        if (index==nums.length){
    
    
            res.add(new ArrayList(temp));
            return;
        }
        //不加入当前层的元素直接继续递归;
        dfs(res,temp,nums,index+1);
        temp.add(nums[index]);//加入当前层的数
        dfs(res,temp,nums,index+1);
        temp.remove(temp.size()-1);
    }

    public static void main(String[] args) {
    
    
        Subset subset=new Subset();
        int [] list=new int[3];
        for (int i=0;i<3;i++){
    
    
            list[i]=i+1;
        }
       System.out.println(subset.subsets(list));
    }
}

Guess you like

Origin blog.csdn.net/yang12332123321/article/details/117132532