首页 > 代码库 > Subsets

Subsets

方法:使用一个vector记录数字是否被选中,惨痛的教训,不要把==写成=。。。。

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> result;
        
        vector<bool> select(nums.size(), false);
        subsets(nums, select, 0, result);
        
        return result;
    }
    
private:
    void subsets(const vector<int> &nums, vector<bool> &select, int step, vector<vector<int>> &result)
    {
        if(step == nums.size())
        {
            vector<int> sub;
            for(int i=0; i<nums.size(); ++i)
            {
                if(select[i])
                    sub.push_back(nums[i]);
            }
            result.push_back(sub);
            return;
        }
        
        select[step] = true;
        subsets(nums, select, step+1, result);
        select[step] = false;
        subsets(nums, select, step+1, result);
    }
};

 

Subsets