Leetcode 78 uses binary state enumeration to solve the subset problem

 

We use one that we know that a subset of an array can be selected and unselected by all elements.

An array of length n has a total of 2^n subsets.

We use an n-bit binary representation, where each bit has two values, 0 and 1, 1 means to take, 0 means not to take. So we enumerate these 2^n states, find out the representation of the corresponding bit, and then add it to the answer array.

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        int n = nums.size();
        vector<vector<int>> res;
        for(int i=0;i<(1<<n);i++){
            vector<int> tmp;
            for(int j=0;j<n;j++){
                if(i&(1<<j)){
                    tmp.emplace_back(nums[j]);
                }
            }
            res.emplace_back(tmp);
        }
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/wwxy1995/article/details/114141875