Get all possible subsets of a set of distinct integers.

This problem asks us to find all possible subsets of a given set of distinct integers. A subset is simply a subset of elements from the given set, and the power set is the set of all possible subsets. Note that the solution set must not contain duplicate subsets.

Problem

Given a set of distinct integers, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> result;
        vector<int> temp;
        result.push_back(temp);
        for(int i = 0; i < nums.size(); i++){
            int size = result.size();
            for(int j = 0; j < size; j++){
                temp = result[j];
                temp.push_back(nums[i]);
                result.push_back(temp);
            }
        }
        return result;
    }
};

int main(){
    Solution s;
    vector<int> nums = {1,2,3};
    vector<vector<int>> result = s.subsets(nums);
    for(int i = 0; i < result.size(); i++){
        for(int j = 0; j < result[i].size(); j++){
            cout << result [i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The approach is to first add the empty subset to the result, and then iterate through the nums array, adding each element to all of the existing subsets to create new subsets.

Evaluated at: 2022-12-11 04:15:50