当前位置:网站首页>Sword finger offer II 079 All subsets

Sword finger offer II 079 All subsets

2022-06-11 02:36:00 Biqiliang

The finger of the sword Offer II 079. All subsets 【 Medium question 】

Ideas :

【 iteration 】【 Binary enumeration 】

And master station 78 The question is the same 78. A subset of

Code :

class Solution {
    
    public List<List<Integer>> subsets(int[] nums) {
    
        // Store all subsets 
        List<List<Integer>> ans = new ArrayList<>();
        // Store the current mask Subset of representation 
        List<Integer> list = new ArrayList<>();
        int n = nums.length;
        // Define a int Type variable mask, Through its binary form   Express  nums  The choice of elements in , Further representation   At present  mask  Corresponding subset 
        for (int mask = 0; mask < (1 << n); mask++) {
    
            // First of all, list To empty , Improve the reusability of variables 
            list.clear();
            // Traverse nums Array , If at present mask Number... From right to left i Bit value is 1, Description in nums The subscript in the array is i The element of is selected , Add it to list Collection 
            for (int i = 0; i < n; i++) {
    
                if ((mask & (1 << i)) != 0){
    
                    list.add(nums[i]);
                }
            }
            // Will the current mask A subset of the representation is added to ans in 
            ans.add(new ArrayList<>(list));
        }
        // All possible mask After being traversed , Got ans That is to say nums All subsets of the array 
        return ans;
    }
}
原网站

版权声明
本文为[Biqiliang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110146475619.html