Implement Power Set

The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set.

For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}.

You may also use a list or array to represent a set.

Example:

Input:  arr = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> subsets(vector<int&nums)
{
    vector<vector<int>> res;
    int n = nums.size();
    if (n == 0)
        return res;
    vector<intx;
    res.push_back(x);
    for (int i = 0i < pow(2n); i++)
    {
        vector<inty;
        for (int j = 0j < nj++)
        {
            if ((i & (1 << j)))
                y.push_back(nums[j]);
        }
        if (find(res.begin(), res.end(), y== res.end())
            res.push_back(y);
    }
    return res;
}
int main()
{
    vector<intnums = {123};
    vector<vector<int>> sub = subsets(nums);

    cout << "[";
    for (int i = 0i < sub.size(); i++)
    {
        cout << "[";
        for (int j = 0j < sub[i].size(); j++)
        {
            cout << sub[i][j];
            if (j != sub[i].size() - 1)
                cout << ",";
        }
        cout << "]";
        if (i != sub.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment