Distinct Subsets

This problem asks you to generate all possible subsets of a given set of distinct integers. For example, if the input is [1,2,3], the output should list all possible subsets: [1], [1,2], [1,2,3], [1,3], [2], [2,3], and [3].

Problem

Given a set of distinct integers, return all possible subsets.
Example input: [1,2,3]
Example output: 
[
  [1],
  [1,2],
  [1,2,3],
  [1,3],
  [2],
  [2,3],
  [3],
]

Solution

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

using namespace std;

void print_vector(vector<int> v) {
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
    cout << endl;
}

void print_vector_vector(vector<vector<int>> v) {
    for (int i = 0; i < v.size(); i++) {
        print_vector(v[i]);
    }
}

vector<vector<int>> subsets(vector<int>& nums) {
    vector<vector<int>> result;
    vector<int> empty;
    result.push_back(empty);
    for (int i = 0; i < nums.size(); i++) {
        int n = result.size();
        for (int j = 0; j < n; j++) {
            vector<int> subset = result[j];
            subset.push_back(nums[i]);
            result.push_back(subset );
        }
    }
    return result;
}

int main() {
    vector<int> nums = {1, 2, 3};
    vector<vector<int>> result = subsets(nums);
    print_vector_vector(result);
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The approach is to first create an empty subset, and then add each element of the given set to all existing subsets to create new subsets. This is a valid approach to solving the problem.

Evaluated at: 2022-11-29 04:15:47