天天看点

Leetcode_78_Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note:

Elements in a subset must be in non-descending order.

The solution set must not contain duplicate subsets.

For example,

If nums = [1,2,3], a solution is:

[

[3],

[1],

[2],

[1,2,3],

[1,3],

[2,3],

[1,2],

[]

]

原文链接

这个题就是一个子集生成的算法,我以前在博客里总结过三种,正好通过这次来复习一下

bool数组法:

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ans;
        bool *sub = new bool[nums.size()+];
        for(int i = ;i<nums.size();i++) sub[i] = false;
        Creat_Vector(nums, ans, sub, , nums.size());
        return ans;
    }

    void Creat_Vector(vector<int>& nums, vector<vector<int>> &ans, bool *sub, int now, int length)
    {

        if(now == length)
        {
            vector<int> subans;
            for(int i = ;i<length;i++)
            {
                if(sub[i]) subans.push_back(nums[i]);
            }
            sort(subans.begin(), subans.end());
            ans.push_back(subans);
        }
        else
        {
            sub[now] = true;
            Creat_Vector(nums, ans, sub, now + , length);
            sub[now] = false;
            Creat_Vector(nums, ans, sub, now + , length);
        }
    }
};